Search code examples
c++eventswxwidgets

How to set multiple events on function


How do you call a function that allready has an event attached to it?

I want to be able to call the function with something like this:

statsDialog::statsDialog(..) : wxDialog(..) {
    updateStats();
}

Or, how to bind multiple eventhandlers to a function? For example call updateStats with the wxEVT_SET_FOCUS event AND when UPDATE_STATS_BUTTON is pressed. How can I do this without duplicating code (copying the updateStats function just changing it to wxFocusEventHandler)?

BEGIN_EVENT_TABLE(statsDialog, wxDialog)
EVT_BUTTON(UPDATE_STATS_BUTTON, statsDialog::updateStats)
END_EVENT_TABLE()

statsDialog::statsDialog(..) : wxDialog(..) {    
    // layout stuff
}

void
statsDialog::updateStats(wxCommandEvent& event) {
    // do stuff on dialog focus AND when UPDATE_STATS_BUTTON is pressed
}

Solution

  • Simply have a function called DoUpdateStats() called from both the focus and button event handlers. This is particularly trivial when using C++11 with Bind():

    Bind(wxEVT_SET_FOCUS, [](wxFocusEvent& e) { e.Skip(); DoUpdateStats(); });
    btn->Bind(wxEVT_BUTTON, [](wxCommandEvent&) { DoUpdateStats(); });