【问题标题】:Simulating a mouse pointer click (can move but can't click)模拟鼠标指针点击(可以移动但不能点击)
【发布时间】:2014-11-21 01:40:19
【问题描述】:

我正在尝试在屏幕上的某个位置模拟鼠标左键单击(和双击)。

我有以下代码:

[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);
}

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

【问题讨论】:

    标签: c# mouseevent


    【解决方案1】:

    我认为你有错误的常量。取自 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);
    }
    

    【讨论】:

    • *Cursor*.Position = new System.Drawing.*Point*(x, y); 给出了上下文错误。我该如何解决这个问题?
    • 好的,我修好了。让我编辑你的答案。谢谢!
    猜你喜欢
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多