|
We have discussed event handling mostly in terms of static event tables because this is the most common way to handle events. However, you can also specify the mapping between events and their handlers at runtime. You might use this method because you want to use different event handlers at different times in your program, or because you are using a different language (such as Python) that can't use static event tables, or simply because you prefer it. Event handlers allow greater granularityyou can turn individual event handlers on and off at runtime, whereas PushEventHandler and PopEventHandler deal with a whole event table. Plus, they allow sharing of event handler functions between different objects. There are two functions associated with dynamic event tables: wxEvtHandler::Connect and wxEvtHandler::Disconnect. Often, you won't need to call wxEvtHandler::Disconnect because the disconnection will happen when the window object is destroyed. Let's use our simple frame class with two event handlers as an example. // Declare our main frame class class MyFrame : public wxFrame { public: // Constructor MyFrame(const wxString& title); // Event handlers void OnQuit(wxCommandEvent& event); void OnAbout(wxCommandEvent& event); private: }; Notice that this time, we do not use the DECLARE_EVENT_TABLE macro. To specify event handling dynamically, we add a couple of lines to our application class's OnInit function: frame->Connect( wxID_EXIT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnQuit) ); frame->Connect( wxID_ABOUT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnAbout) ); We pass to Connect the window identifier, the event identifier, and finally a pointer to the event handler function. Note that the event identifier (wxEVT_COMMAND_MENU_SELECTED) is different from the event table macro (EVT_MENU); the event table macro makes use of the event identifier internally. The wxCommandEventHandler macro around the function name is necessary to appease the compilercasts are done by static event table macros automatically. In general, if you have a handler that takes an event called wxXYZEvent, then in your Connect call, you will wrap the function name in the macro wxXYZEventHandler. If we want to remove the mapping between event and handler function, we can use the wxEvtHandler::Disconnect function, as follows: frame->Disconnect( wxID_EXIT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MyFrame::OnQuit) ); frame->Disconnect( wxID_ABOUT, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventFunction(MyFrame::OnAbout) ); |
|