方法一:需要調用win32api,winform、wpf通用
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14[DllImport("user32.dll")]
public static extern bool GetCursorPos(out POINT lpPoint);
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
this.X = x;
this.Y = y;
}
}
方法二:通過調用Win32 API設置鼠標位置,實現移到指定位置,模仿並實現鼠標點擊動作,並回到鼠標原先位置的方法,代碼如下:
//獲取屏幕
int width = (int)SystemParameters.PrimaryScreenWidth;//得到屏幕整體寬度
int height = (int)SystemParameters.PrimaryScreenHeight;//得到屏幕整體高度
//獲取鼠標初始位置,相對屏幕的絕對位置
System.Drawing.Point p = new System.Drawing.Point();
ApiHelper.GetCursorPos(out p);
if (width != 0) p.X = 65535 * p.X / width;
if (height != 0) p.Y = 65535 * p.Y / height;
//設置移動的位置坐標
int dy = 100;
int dx = 100;
dx = (int)(dx * 65535 / width);
dy = (int)(dy * 65535 / height);
//移到指定位置
ApiHelper.mouse_event((int)(MouseEventFlag.MOUSEEVENTF_MOVE | MouseEventFlag.MOUSEEVENTF_ABSOLUTE), dx, dy, 0, IntPtr.Zero);//移動到需要點擊的位置
//完成一次點擊
ApiHelper.mouse_event((int)(MouseEventFlag.MOUSEEVENTF_LEFTDOWN), 0, 0, 0, IntPtr.Zero);
ApiHelper.mouse_event((int)(MouseEventFlag.MOUSEEVENTF_LEFTUP), 0, 0, 0, IntPtr.Zero);//
//單擊可以寫為
ApiHelper.mouse_event((int)(MouseEventFlag.MOUSEEVENTF_LEFTDOWN | MouseEventFlag.MOUSEEVENTF_LEFTUP), 0, 0, 0, IntPtr.Zero);
//雙擊則再重復單擊方法
//回到初始位置
ApiHelper.mouse_event((int)(MouseEventFlag.MOUSEEVENTF_MOVE | MouseEventFlag.MOUSEEVENTF_ABSOLUTE), p.X, p.Y, 0, IntPtr.Zero);//移動到需要點擊的位置
代碼中ApiHelper為作者封裝的Win32 API方法,讀者可以通過api精靈等軟件查詢api函數,自行實現封裝。