I’m trying to send mouse events to a window in windows through the SendMessage(..) method.
The problem I’m facing is that the messages don’t seem to be delivered to the window I’m sending them to, even though SendMessage returns 0, which(according to the documentation) means the message was delivered successfully.
I’m using the following piece of code:
(Let p be a Point struct and selectedWindow.Handle a valid handle to a window)
int position = ((p.X & 0xFFFF) << 16) | (p.Y & 0xFFFF);
SendMessage(selectedWindow.Handle, 0x0201, new IntPtr(), new IntPtr(position));
SendMessage(selectedWindow.Handle, 0x0202, new IntPtr(), new IntPtr(position));
0x0201 and 0x0202 are WM_LBUTTONDOWN and WM_LBUTTONUP.
Could someone enlighten me why this isn’t working?
(Edit: I am using the ScreenToClient() method to convert a screen position to a position within the window)
Mouse messages are normally retrieved from the message queue, which means you should use PostMessage(). But it isn’t that likely that this is the real problem, very few programs do mouse handling in the message loop. UAC is an obvious failure scenario, you cannot send messages to a window owned by an elevated program. You send the wrong WParam value, that could have an effect. And of course you could have the wrong window handle.
But the much more likely cause is the code we cannot see. You seem to go through some trouble to generate the X- and Y-coordinates of the message. No such effort is necessary, it doesn’t matter where you click the button. You might as well click it at (1, 1):
Or in other words, mouse coordinates are relative from the window’s upper left corner. Additional hacks are generating the BM_CLICK message and whatever WM_COMMAND message the button generates.
Use the Spy++ tool to observe the message processing.