C# 我应该怎么做才能使这段代码在VS2010中正常工作?
我已经手动使用这段代码来模拟系统通过代码单击鼠标C# 我应该怎么做才能使这段代码在VS2010中正常工作?,c#,visual-studio-2010,mouse,mouseevent,C#,Visual Studio 2010,Mouse,Mouseevent,我已经手动使用这段代码来模拟系统通过代码单击鼠标 using System; using System.Windows.Forms; using System.Runtime.InteropServices; public class Form1 : Form { [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)] public s
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class Form1 : Form
{
[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
private const int MOUSEEVENTF_LEFTDOWN = 0x02;
private const int MOUSEEVENTF_LEFTUP = 0x04;
private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
private const int MOUSEEVENTF_RIGHTUP = 0x10;
public Form1()
{
}
public void DoMouseClick()
{
//Call the imported function with the cursor's current position
int X = Cursor.Position.X;
int Y = Cursor.Position.Y;
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
}
//...other code needed for the application
}
但是现在我正在使用VS2010和Windows7,我现在在执行这段代码时遇到了错误
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
所以对此有什么建议
我遇到的错误是:
检测到PinvokesTack不平衡
调用PInvoke函数“ClickingApp!”!单击app.Form1::mouse_event'使堆栈不平衡。这可能是因为托管PInvoke签名与非托管目标签名不匹配。检查PInvoke签名的调用约定和参数是否与目标非托管签名匹配
问题在于p/Invoke签名,请尝试以下操作
[DllImport("user32.dll")]
static extern void mouse_event(uint dwFlags, uint dx, uint dy,
uint dwData, UIntPtr dwExtraInfo);
DWORD是32位,而C#long是64位
还注意到您正在指定调用约定,最好不要在Windows API使用p/Invoke时指定它,或者您可以使用CallingConvention。Winapi,错误的调用约定通常是导致堆栈不平衡的原因。请您解释一下调用约定,因为我不知道它…:$@Mobin,调用约定定义了如何将参数传递给函数,以及函数完成时谁负责清理堆栈。例如,C中的一个典型调用约定,参数按相反顺序推送到堆栈上,调用方负责堆栈清理,stdcall调用约定是函数本身负责清理堆栈等。函数使用特定的调用约定编译,如果调用方使用错误的约定,堆栈将处于不一致状态。