问题
I created a button in c++ as follows:
HWND btn = CreateWindow(
"BUTTON",
"OK",
WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
10,
10,
100,
100,
hWnd,
NULL,
(HINSTANCE)GetWindowLong(hWnd, GWL_HINSTANCE),
NULL);
The button is displayed in the main window (hWnd) but I don't know how or where to give it an event handler. Any help please?
回答1:
There are three ways to detect the button being clicked.
The preferred approach is to add a WM_COMMAND handler to the window procedure of the button's parent window. When the button is clicked, it sends a BN_CLICKED notification to its parent window. This is described in the MSDN documentation for buttons:
Handling Messages from a Button
Notification Messages from Buttons
If you are adding the button to a parent window that you do not own, you can subclass the parent window using SetWindowsLongPtr(GWL_WNDPROC) or SetWindowSubClass(), and then you can handle messages that are sent to it, such as
BN_CLICKED
. This only works if the subclassing code runs in the same thread that owns the parent window.Alternatively, you can subclass the button itself and handle keyboard and mouse messages instead.
Another option is to set an event hook using SetWinEventHook() asking to receive
EVENT_OBJECT_INVOKED
events. In the event callback procedure, the providedhwnd
,ID
, andidChild
parameters will identify the control that is being invoked, such as a clicked button.
回答2:
When the button is clicked, it sends a BN_CLICKED notification message (carried by the WM_COMMAND message) to its parent window. The BN_CLICKED
notification code is in the HIWORD
of the wParam
of the message. The LOWORD
of the wParam
of the message has the ID of the button. The lParam
of the message has the HWND
of the button. This is all in the online Windows docs. Google for BN_CLICKED
.
Consider this pseudo code... it's from memory. Basically, add the stuff inside the WM_COMMAND
case to the window procedure that you already have:
LRESULT WINAPI YourWindowProc(HWND hWnd, UINT nMsg, WPARAM wp, LPARAM lp)
{
switch (nMsg)
{
case WM_COMMAND:
{
switch (HIWORD(wp))
{
case BN_CLICKED:
{
switch (LOWORD(wp))
{
case IDC_BUTTON1: // or whatever the ID of your button is...
{
// do stuff for button...
break;
}
}
break;
}
}
break;
}
default:
return DefWindowProc(hWnd, nMsg, wp, lp);
}
return 0;
}
来源:https://stackoverflow.com/questions/41173176/add-event-handler-to-button-in-c