Lukas Šalkauskas solution has been working for me for quite some time, but today it suddenly led to the following error (perhaps due to some .NET updates from Windows Update?)
The call to the PInvoke "SampleMethod" function is an unbalanced stack. This is likely due to the fact that the PInvoke managed signature does not match the unmanaged target signature. Verify that the calling agreement and PInvoke signature settings match the target unmanaged signature.
So, I switched to pinvoke.net code example , and now it works well:
[DllImport("user32.dll")] static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo); [Flags] public enum MouseEventFlags { LEFTDOWN = 0x00000002, LEFTUP = 0x00000004, MIDDLEDOWN = 0x00000020, MIDDLEUP = 0x00000040, MOVE = 0x00000001, ABSOLUTE = 0x00008000, RIGHTDOWN = 0x00000008, RIGHTUP = 0x00000010 } public static void LeftClick(int x, int y) { Cursor.Position = new System.Drawing.Point(x, y); mouse_event((int)(MouseEventFlags.LEFTDOWN), 0, 0, 0, 0); mouse_event((int)(MouseEventFlags.LEFTUP), 0, 0, 0, 0); }
Ohad schneider
source share