我已经手动使用此代码通过代码模拟系统的鼠标点击。
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
}
但现在我使用的是 VS 2010 和 Windows 7,现在执行此代码时出现错误
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
所以对此有什么建议......
我遇到的错误是:
PInvokeStackImbalance was Detected
A call to PInvoke function 'ClickingApp!ClickingApp.Form1::mouse_event' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.
最佳答案
问题出在 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,错误的调用约定通常是堆栈不平衡的原因.
关于c# - 我应该怎么做才能使这段代码在 VS 2010 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3206529/