Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add event handler to button in c++

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?

like image 716
Werner Avatar asked Oct 26 '25 23:10

Werner


1 Answers

There are three ways to detect the button being clicked.

  1. 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

  2. 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.

  3. Another option is to set an event hook using SetWinEventHook() asking to receive EVENT_OBJECT_INVOKED events. In the event callback procedure, the provided hwnd, ID, and idChild parameters will identify the control that is being invoked, such as a clicked button.

like image 66
Remy Lebeau Avatar answered Oct 28 '25 11:10

Remy Lebeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!