Simulating Mouse Clicks in C# with mouse_event


You can simulate mouse movement and clicks using the mouse_event win32 API. This is just one way to do this, I’ll be posting at least two other ways to do this, each has there own pros and cons.
This uses pInvoke to call the win32 API, and it sends a command and the coordinates to click specified in mickeys. Use the MOUSEEVENTF_ABSOLUTE to specify you want to use absolute positioning, otherwise the mouse_event API will assume you want to use relative positioning and will move the mouse by adding your X and Y coordinates to the last position.

mouse_event Code in C#


[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(uint dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
private const int MOUSEEVENTF_ABSOLUTE = 0x8000;
private const int MOUSEEVENTF_LEFTDOWN = 0x0002;
private const int MOUSEEVENTF_LEFTUP = 0x0004;
private const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;
private const int MOUSEEVENTF_MIDDLEUP = 0x0040;
private const int MOUSEEVENTF_MOVE = 0x0001;
private const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
private const int MOUSEEVENTF_RIGHTUP = 0x0010;
private const int MOUSEEVENTF_WHEEL = 0x0800;
private const int MOUSEEVENTF_XDOWN = 0x0080;
private const int MOUSEEVENTF_XUP = 0x0100;         
//.................................
//In your own function: 
int X = 1220;
int Y = 13;
mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, X, Y, 0, 0);
mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
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.

You can use that to convert the input in pixels to the desired value, like this:
var inputXinPixels = 200;
var inputYinPixels = 200;
var screenBounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
var outputX = inputXinPixels * 65535 / screenBounds.Width;
var outputY = inputYinPixels * 65535 / screenBounds.Height;
MoveTo(outputX, outputY);
Please keep in mind that this may not be correct for multiple monitors. Also notice that the documention says:
This function has been superseded. Use SendInput instead.

If I were in your position I would use Cursor.Position. The following code works as expected:
System.Windows.Forms.Cursor.Position = new System.Drawing.Point(200, 200);