本文只涉及简单用法,园子中有大神详细记录各参数示意。
引用user32.dll(文件在系统C:\Windows\System32中),可模拟鼠标 点击 事件。
1 [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] 2 private static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo); 3 [DllImport("user32.dll")] 4 public static extern bool GetCursorPos(out Point pt);//获取鼠标焦点 5 [DllImport("user32.dll")] 6 public static extern void SetCursorPos(int x, int y);//设置鼠标焦点
注意:每个函数引用都需要DLLImport一次!
const int MOUSEEVENTF_MOVE = 0x0001; //移动鼠标 const int MOUSEEVENTF_LEFTDOWN = 0x0002; //模拟鼠标左键按下 const int MOUSEEVENTF_LEFTUP = 0x0004; //模拟鼠标左键抬起 const int MOUSEEVENTF_RIGHTDOWN = 0x0008; //模拟鼠标右键按下 const int MOUSEEVENTF_RIGHTUP = 0x0010; //模拟鼠标右键抬起 const int MOUSEEVENTF_MIDDLEDOWN = 0x0020; //模拟鼠标中键按下 const int MOUSEEVENTF_MIDDLEUP = 0x0040; //模拟鼠标中键抬起 const int MOUSEEVENTF_ABSOLUTE = 0x8000; //标示是否采用绝对坐标
mouse_event()使用实例:
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, Cursor.Position.X, Cursor.Position.Y, 0, 0);//Cursor.Position.X, Cursor.Position.Y指示鼠标所在绝对位置 mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 800, 450, 0, 0);//(800*450)鼠标左键点击屏幕中央
绝对位置表示相对于屏幕左上角的坐标,即左上角坐标为(0,0)。
获取与设置焦点:
Point p; GetCursorPos(out p); SetCursorPos(400, 450);