How can I simulate a button click given the handle to the button's window?

Send a BM_CLICK message to the HWND of the button:

SendMessage(hButton, BM_CLICK, 0, 0);

That causes the button to receive WM_LBUTTONDOWN and WM_LBUTTONUP messages, and the parent to receive an BN_CLICKED notification, as if the user had physically clicked on the button.


Find the handle to the button that you want to click (by using FindWindowEx), and just send click message:

SendMessage(hButton, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(0, 0));
SendMessage(hButton, WM_LBUTTONUP, MK_LBUTTON, MAKELPARAM(0, 0));

SendMessage(hParent, WM_COMMAND, MAKEWPARAM(IdOfButton, BN_CLICKED), (LPARAM)hwndOfButton);

Typically you can get away without the hwndOfButton, if you don't know it - depends on the dialog's implementation!

It can be SendMessage or PostMessage, depending on your use case.

Tags:

C++

Winapi

Button