C#控制鼠标动作
可以通过两个函数操作鼠标:
[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);
[DllImport("user32.dll")]
static extern void mouse_event(MouseEventFlag flags, int dx, int dy, uint data, UIntPtr extraInfo);
[Flags]
enum MouseEventFlag : uint
{
Move = 0x0001,
LeftDown = 0x0002,
LeftUp = 0x0004,
RightDown = 0x0008,
RightUp = 0x0010,
MiddleDown = 0x0020,
MiddleUp = 0x0040,
XDown = 0x0080,
XUp = 0x0100,
Wheel = 0x0800,
VirtualDesk = 0x4000,
Absolute = 0x8000
}
SetCursorPos使鼠标移动到指定位置;mouse_event使用MouseEventFlag枚举中的Move,也可以使鼠标移动。
mouse_event中使用不同的枚举值可以模拟不同的鼠标事件。
值得注意的是有几点:
第一步:移动鼠标到(10,10)处,用SetCursorPos(10, 10);
第二步:触发左键,用mouse_event(MouseEventFlag.LeftDown, 0, 0, 0, UIntPtr.Zero);
本质上是两步的事件,不能把window API 想的太聪明,认为它会自动跑到(10,10)处,再左键
鼠标左键按下和松开两个事件的组合即一次单击:
mouse_event (MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0 )
两次连续的鼠标左键单击事件 构成一次鼠标双击事件:
mouse_event (MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0 )
mouse_event (MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0 )
这里要注意,指定Absolute,鼠标的坐标会被约束在[0, 65535]之间。0即对应屏幕左,65535即对应屏幕右下角。
MSDN原话如下:
If MOUSEEVENTF_ABSOLUTE value is specified, dx and dy contain normalized absolute coordinates between 0 and 65,535. The event procedure maps these coordinates onto the display surface. Coordinate (0,0) maps onto the upper-left corner of the display surface, (65535,65535) maps onto the lower-right corner.
所以模拟在(10, 10)处的左键,代码应改为:
mouse_event(MOUSEEVENTF_LEFTDOWN, 10 * 65536 / Screen.PrimaryScreen.Bounds.Width, 10 * 65536 / Screen.PrimaryScreen.Bounds.Height, 0, 0);
如果显示器是一拖二的,想在第二个屏上使用mouse_event,就不能用Screen.PrimaryScreen了