Windows mouse click simulation

I am writing a remote desktop clone in C ++ using QT. So far I can move the mouse cursor in order. For this, QT has a nice setPos function. However, I lost a bit of information about which API / Library should be used to simulate mouse clicks.

One of the methods that I know of is to send WM_ (event) to the window using the HWND window. However, I was hoping there was a more important method for full control of the mouse. Is there any other way to tell the operating system that the left mouse button is pressed?

Thanks.

+2
qt button click mouse simulate
source share
3 answers

This is in C #, but may help you understand:

[DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)] public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo); private const int MOUSEEVENTF_LEFTDOWN = 0x02; private const int MOUSEEVENTF_LEFTUP = 0x04; private const int MOUSEEVENTF_RIGHTDOWN = 0x08; private const int MOUSEEVENTF_RIGHTUP = 0x10; public void DoMouseClick() { int X = Cursor.Position.X; int Y = Cursor.Position.Y; mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0); } 

Resources that can help:

http://msdn.microsoft.com/en-us/library/ms646260%28VS.85%29.aspx

http://www.codeguru.com/Cpp/WP/win32/article.php/c4543/

+2
source share

Combining all the togegher, here is the code for Qt:

 #include <windows.h> QApplication::desktop()->cursor().setPos(globalX,globalY); mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 1, 1, 0, 0); 
+9
source share

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); } 
+3
source share

All Articles