Before version 2.0 of wxWidgets, events were handled by the application either by supplying callback functions, or by overriding virtual member functions such as OnSize.

From wxWidgets 2.0, event tables are used instead, with a few exceptions.

An event table is placed in an implementation file to tell wxWidgets how to map events to member functions. These member functions are not virtual functions, but they are all similar in form: they take a single wxEvent-derived argument, and have a void return type.

Here's an example of an event table.

  EVT_MENU    (wxID_EXIT, MyFrame::OnExit)
  EVT_MENU    (DO_TEST,   MyFrame::DoTest)
  EVT_SIZE    (           MyFrame::OnSize)
  EVT_BUTTON  (BUTTON1,   MyFrame::OnButton1)

The first two entries map menu commands to two different member functions. The EVT_SIZE macro doesn't need a window identifier, since normally you are only interested in the current window's size events.

The EVT_BUTTON macro demonstrates that the originating event does not have to come from the window class implementing the event table - if the event source is a button within a panel within a frame, this will still work, because event tables are searched up through the hierarchy of windows for the command events. In this case, the button's event table will be searched, then the parent panel's, then the frame's.

As mentioned before, the member functions that handle events do not have to be virtual. Indeed, the member functions should not be virtual as the event handler ignores that the functions are virtual, i.e. overriding a virtual member function in a derived class will not have any effect. These member functions take an event argument, and the class of event differs according to the type of event and the class of the originating window. For size events, wxSizeEvent is used. For menu commands and most control commands (such as button presses), wxCommandEvent is used. When controls get more complicated, then specific event classes are used, such as wxTreeEvent for events from wxTreeCtrl windows.

As well as the event table in the implementation file, there must also be a DECLARE_EVENT_TABLE macro somewhere in the class declaration. For example:

class MyFrame : public wxFrame
  void OnExit(wxCommandEvent& event);
  void OnSize(wxSizeEvent& event);

  int       m_count;


Note that this macro may occur in any section of the class (public, protected or private) but that it is probably better to insert it at the end, as shown, because this macro implicitly changes the access to protected which may be quite unexpected if there is anything following it.

Finally, if you don't like using macros for static initialization of the event tables you may also use wxEvtHandler::Connect to connect the events to the handlers dynamically, during run-time. See the event sample for an example of doing it.

ymasuda 平成17年11月19日