模拟鼠标指针点击(可以移动,但不能点击)

本文关键字:但不能 移动 鼠标指针 模拟 | 更新日期: 2023-09-27 18:24:40

我试图模拟鼠标左键点击(和双击)屏幕上的某个位置。

我有以下代码:

[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool SetCursorPos(int x, int y);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
public const int MOUSEEVENTF_LEFTDOWN = 0x02;
public const int MOUSEEVENTF_LEFTUP = 0x04;
//This simulates a left mouse click
public static void LeftMouseClick(int xpos, int ypos)
{
     SetCursorPos(xpos, ypos);
     mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0);
     mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0);
}

我可以用上面的代码将鼠标指针移动到坐标上,但我无法点击(或双击)。

模拟鼠标指针点击(可以移动,但不能点击)

我认为您的常量错误。取自pinvoke.net:

[DllImport("user32.dll")]
static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
[Flags]
public enum MouseEventFlags
{
    LEFTDOWN = 0x00000002,
    LEFTUP = 0x00000004,
    MIDDLEDOWN = 0x00000020,
    MIDDLEUP = 0x00000040,
    MOVE = 0x00000001,
    ABSOLUTE = 0x00008000,
    RIGHTDOWN = 0x00000008,
    RIGHTUP = 0x00000010
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool SetCursorPos(int x, int y);
public static void LeftClick(int x, int y)
{
    SetCursorPos(x, y);
    mouse_event((int)(MouseEventFlags.LEFTDOWN), 0, 0, 0, 0);
    mouse_event((int)(MouseEventFlags.LEFTUP), 0, 0, 0, 0);
}
相关文章: