鼠标单击代码

时间:2012-03-20 15:36:19

标签: c# click mouse

我正试图通过代码点击桌面,所以我做到了:

    public static void MouseLeftClick(Point pos)
    {
        System.Windows.Forms.Cursor.Position = pos;
        mouse_event(MOUSEEVENTF_LEFTDOWN, pos.X, pos.Y, 0, 0);
        mouse_event(MOUSEEVENTF_LEFTUP, pos.X, pos.Y, 0, 0);
    }

我意识到只有添加System.Windows.Forms.Cursor.Position = pos才有效; 为什么? mouse_event x,y参数没用?

1 个答案:

答案 0 :(得分:2)

您是否阅读过mouse_event函数的description

例如,如果仅使用RIGHTDOWN,则X和Y参数不代表设置鼠标的坐标。

以下是处理mouse _ event:

的方法
[DllImport("user32.dll")]
private static extern void mouse_event(MouseEventFlags dwFlags, uint dx, uint dy, uint dwData, UIntPtr dwExtraInfo);

...

// Converts into pixels
uint x = (uint)(pos.X * 65535 / Screen.PrimaryScreen.Bounds.Width);
uint y = (uint)(pos.Y * 65535 / Screen.PrimaryScreen.Bounds.Height);

// Moves the mouse (absolute)
mouse_event(MouseEventFlags.MOVE | MouseEventFlags.ABSOLUTE, x, y, 0, UIntPtr.Zero);

// Now button down
mouse_event(MouseEventFlags.RIGHTDOWN, 0, 0, 0, UIntPtr.Zero);
mouse_event(MouseEventFlags.RIGHTUP, 0, 0, 0, UIntPtr.Zero);

当然,设置光标位置比使用mouse_event告诉您的鼠标移动要简单得多。

顺便说一下,这个功能已被取代。请改用SendInput