You can use two functions to operate the mouse:
[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 allows the mouse to Move to the specified position. mouse_event uses the Move in the MouseEventFlag enumeration to Move the mouse.
Different enumerated values can be used in mouse_event to simulate different mouse events.
Note the following points:
1. we cannot use mouse_event (MouseEventFlag. leftDown, 10, 10, 0, UIntPtr. zero); to simulate the left-click event at (10, 10), we need to split this step into two steps:
Step 1: Move the mouse to (10, 10) and use SetCursorPos (10, 10 );
Step 2: trigger the left button and use mouse_event (MouseEventFlag. LeftDown, 0, 0, 0, UIntPtr. Zero );
Essentially a two-step event, the window API cannot be too intelligent to think that it will automatically run to (10, 10), and then left-click
2. The enumerated values of MouseEventFlag can be used together. | Operator is used.
By clicking the left mouse button and releasing the combination of the two events, you can click:
Mouse_event (MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0)
Two consecutive left-click events constitute a double-click event:
Mouse_event (MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0)
Mouse_event (MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0)
3. There is an Absolute enumeration in the MouseEventFlag. If no Absolute is specified, the operation of mouse_event is relative to the position of the last mouse; if Absolute is specified, it is relative to the whole screen coordinate.
Note that if you specify Absolute, the coordinates of the mouse are constrained between [0, 65535. 0 corresponds to the left of the screen, and 65535 corresponds to the bottom right corner of the screen.
The original MSDN statement is as follows:
If MOUSEEVENTF_ABSOLUTE value is specified,DxAndDyContain 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.
So the simulated left button at (10, 10) should be changed:
Mouse_event (MOUSEEVENTF_LEFTDOWN, 10*65536/Screen. PrimaryScreen. Bounds. Width, 10*65536/Screen. PrimaryScreen. Bounds. Height, 0, 0 );
If you want to use mouse_event on the second Screen, you cannot use Screen. PrimaryScreen.