1
votes

I am creating program in C++ (Windows 7 ), that controls one specific window by reading its screen and sending back mouse signals (only left-clicks). I am using WinAPI obviously. Problem is with the mouse signals. My target is to send mouse events independently on actual cursor position. (i.e. it can run on "the background" and the window does not have to be visible).

I tried the obvious solution using SendMessage (or PostMessage):

PostMessage(hwnd, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(x, y));
this_thread::sleep_for (std::chrono::milliseconds(100));
PostMessage(hwnd, WM_LBUTTONUP  , MK_LBUTTON, MAKELPARAM(x, y));

I think the commands work fine but there is some problem with how the application process the click events. It seems it does not take into account the parameters x,y and instead when WM_LBUTTONUP is called, it asks OS where the cursor is and make the click on that location. So in the end the click occurs always on the location of cursor (if it is inside the window).

I also tried to send WM_MOUSEMOVE event before WM_LBUTTONUP but it didn't help.

This behavior is really strange, and I fully blame the application not WinAPI. Any ideas how to solve this? Can I maybe somehow trick the window so it thinks that cursor is elsewhere?

1
"Any ideas how to solve this?" - Well if your target application is retrieving the current mouse position instead of using the coordinates passed with the message you need to fix the target application. - Captain Obvlious
Why are people obsessed with the idea, that faking input would be a good option to automate a UI, instead of going for the straight forward solution, and use UI Automation? It's there for a reason. @milevyo: SendInput requires, that the application is visible, the foreground window, and the desired location not obscured by any other window. No need to try. - IInspectable
@IInspectable, agree, but i have never seen a working example. can you post one? - milevyo
@milevyo Really, you cannot find an example of UI Automation by websearch? - David Heffernan

1 Answers

1
votes

If this is the only thing you need then use SendInput with the MOUSEINPUT structure.

If you want to understand why then read on. What you are doing does not work because mouse messages are special. They are not regular messages that arrive and wait for you in the message queue. They are synthesized on demand when you call GetMessage and therefore they get their data from a secret, hidden place . In fact, generally speaking input messages are treated differently than posted messages. Here is some reading material.