How can I simulate a button click given the handle

2019-03-26 03:24发布

I want to simulate a click on a button located in a dialog box.

I have the handle to that window. This is an Abort/Retry/Ignore kind of window.

I don't want to go with simulating a click having X and Y coordinates as it doesn't suit my needs.

5条回答
一纸荒年 Trace。
2楼-- · 2019-03-26 03:41

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.

查看更多
Bombasti
3楼-- · 2019-03-26 03:43

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.

查看更多
混吃等死
4楼-- · 2019-03-26 03:47

Try this for OK:

SendMessage(hWnd, WM_COMMAND, 1, NULL);
查看更多
淡お忘
5楼-- · 2019-03-26 03:54

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));
查看更多
Fickle 薄情
6楼-- · 2019-03-26 04:02

Here is a complete function:

void clickControl(HWND hWnd, int x, int y)
{
    POINT p;
    p.x = x; p.y = y;
    ClientToScreen(hWnd, &p);
    SetCursorPos(p.x, p.y);
    PostMessage(hWnd, WM_MOUSEMOVE, 0, MAKELPARAM(x, y));
    PostMessage(hWnd, WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(x, y));
    PostMessage(hWnd, WM_LBUTTONUP, MK_LBUTTON, MAKELPARAM(x, y));
}
查看更多
登录 后发表回答