C++: Send Mouse Click using PostMessage/SendMessage

Forivin picture Forivin · Nov 24, 2013 · Viewed 7.4k times · Source

I'm at the moment trying to send a right click to a computergame without affecting my visible mouse pointer.
I'm not sure if the game just doesn't like it or if I'm doing something wrong. Here is the short-version of my code:

WORD tx = 500;
WORD ty = 500;
HWND windowHandle = FindWindow(NULL,TEXT("Game title"));
if (windowHandle != 0) {
    SendMessage(windowHandle, WM_RBUTTONDOWN, MK_RBUTTON, MAKELPARAM(tx, ty));
    Sleep(50);
    SendMessage(windowHandle, WM_RBUTTONUP, MK_RBUTTON, MAKELPARAM(tx, ty));
    Sleep(50);
    std::cout << "message sent..." << std::endl;
}

I tried this many times and made sure that the games window is on top and active etc, but the game won't register my click.. ("message sent..." is printed every time though)
I know that I could also use SendInput, but first I want to make sure that it is really not possible using PostMessage.

Answer

Aakash Goyal picture Aakash Goyal · Nov 24, 2013

I used the below method to simulate a right mouse click in Qt/C++. See if it works :

mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_RIGHTDOWN, nX, nY, 0, 0); mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_RIGHTUP, nX, nY, 0, 0);

The libraries to be used were windows.h and winuser.h