Home > Articles > Programming > User Interface (UI)

  • Print
  • + Share This
Like this article? We recommend

Handling Events

A program isn’t worth much if it doesn’t do anything in response to user events such as clicks of buttons and menus. The wxWidgets library contains a powerful event-handling mechanism that’s surprisingly easy to use compared to a lot of other C++ event mechanisms.

In a nutshell, you simply write your member functions that will respond to certain events. Then you list these events in an event table, and wxWidgets does the rest.

Here’s the event table code that attaches the events in Listing 1:

 EVT_BUTTON(BUTTON1, MyFrame::OnButton1)
 EVT_BUTTON(BUTTON2, MyFrame::OnButton2)
 EVT_MENU(Minimal_Quit, MyFrame::OnQuit)
 EVT_MENU(Minimal_About, MyFrame::OnAbout)

This code is really a bunch of macros:

  1. For the first line, pass BEGIN_EVENT_TABLE the name of your own class (in this case, MyFrame), and the name of the wxWidgets class from which your class is derived (in this case, wxFrame).
  2. List a macro for each event you want to capture. For button clicks, simply type EVT_BUTTON, passing the control ID and the function you want to call. For the button whose ID is BUTTON1, for example, I wanted the member function OnButton1 of MyFrame to be called when the button is clicked. Thus, I pass the following to the EVT_BUTTON macro:
    BUTTON1, MyFrame::OnButton1
  3. The list box control has several events. We want to respond to the double-click event, so use a macro called EVT_LISTBOX_DCLICK. For menu item clicks, use the EVT_MENU macro. In all these cases, pass the ID followed by the function you want to call in response to the event.
  4. After you finish listing the events, wrap it up with a call to the END_EVENT_TABLE macro.

Believe it or not, that’s all you have to do to tie your code to events. Thus, when this program runs, and you click the first button in the window, the MyFrame::OnButton1 function runs.

  • + Share This
  • 🔖 Save To Your Account