Background mouse click at (x,y)

Hello everyone, so i am scouting and browsing around to see if there is any way i could perform a background mouse click to (x,y) coordinates without moving the cursor.

I have already found a way to perform a mouse click at (x,y) relative to a HWND window, but this involves the function


which moves the mouse to the given location, which i am trying to avoid now. So, is there anyway i could perform a mouse click at a given (x,y) position, without moving the cursor. I need it to be background capable.

I have tested with the following code

HWND hwnd = FindWindowA(NULL, "Untitled - Notepad");
PostMessage(hwnd, WM_LBUTTONDOWN, MK_LBUTTON, BuildParam(509, 18));
PostMessage(hwnd, WM_LBUTTONUP, MK_LBUTTON, BuildParam(509, 18));

where the coordinates (509,18) is suppose to be the position of the exit button in the top right. It is something with the coordinates i think, because my button click does register if i do SetCursorPos(509, 18); before the PostMessage functions.
Last edited on
Using GetCursorPos(...) you could move the cursor to the position and then restore the old position. This might be that fast that the user would not recognize it.

An alternative would be to impersonate the button click itself using BM_CLICK:

Note the in this case you probably need to [temporary] change the active window.
This plan is fraught with little complications.

You may end up getting this working for most cases, but in particular if the user is moving the mouse while you're doing this, there will be several move messages interrupting the flow of instructions, and they could click buttons themselves.

I assume you're not in control of the recipient application's source code.

That said, one thing you can do to help yourself is switch to sendmessage instead of postmessage. Postmessage puts messages in the cue, but that mixes into the existing cue of messages. If you use sendmessage, the message is sent at that time (with caveats).

@coder777's point assumes you're really attempting to click on a button, and is a superior choice if so (and still may do well to consider send instead of post).

Taking @coder777's point to the next level, you may discover the application you're attempting to control has custom message traffic, which you might discover with spy++, and if you figure out what they mean you might do even better by sending one of those messages instead, if applicable.
Registered users can post here. Sign in or register to post.