I got a WM_COMMAND in a button event by Spy++, It looks like:
<000116> 001B0A02 S WM_NOTIFY idCtrl:133978 pnmh:0019F9A0
<000117> 001B0A02 R WM_NOTIFY
<000118> 001B0A02 S WM_COMMAND wNotifyCode:0000 wID:2 hwndCtl:00020B5A
<000119> 001B0A02 R WM_COMMAND
<000120> 001B0A02 S WM_NOTIFY idCtrl:133978 pnmh:0019F9BC
<000121> 001B0A02 R WM_NOTIFY
Then I tried to redo WM_COMMAND
by SendMessage
:
Nothing happened. I used the AHK script to be sure, same result.
When I used SendMessage()
, Spy++ got this:
<000423> 001B0A02 S WM_COMMAND wNotifyCode:0000 wID:2 hwndCtl:00000014
<000424> 001B0A02 R WM_COMMAND
I also let the lParam = 0
, then it worked but not as I expected, another Menu item opened.
<000001> 001B0A02 S WM_COMMAND wNotifyCode:0 (sent from a menu) wID:2
So how can I do this?
To emulate the WM_COMMAND
for a button click, you need to send the ID of your button and the BN_CLICKED
notification code (combined) as the wParam
argument to SendMessage()
, and the handle (HWND
) of the button as the lParam
.
If hDlg
is the handle of your dialog window, and IDC_MYBUTTON
is the resource ID of your button, the call would be like this:
SendMessage(hDlg, WM_COMMAND, MAKEWPARAM(IDC_MYBUTTON, BN_CLICKED), (LPARAM)GetDlgItem(hDlg, IDC_MYBUTTON));
As it happens, the BN_CLICKED
notification code has a value of 0
, so the wParam
value will be just the control ID; this appears to be 2
in your case – the value used by Windows for the "Cancel" button. The problem, in your code, seems to be an invalid window handle for the lParam
argument.