Search code examples
c++eventswxwidgets

How to click a Button in wxWidgets handler OnClose?


I have a handler for the close button (upper right corner) in a dialog and a handler for an addition button inside the dialog. My custom button has wxID_CANCEL as ID. The handler OnClose should execute the handler OnButtonCancel. What happens: it closes the dialog and the app, because the dialog is in a overwritten wxApp:OnInit. But OnButtonCancel is not executed.

void Dialog_Test::OnClose(wxCloseEvent& event) {
    wxCommandEvent event_button_clicked(wxEVT_COMMAND_BUTTON_CLICKED, wxID_CANCEL);
    event_button_clicked.SetEventObject(this);
    this->ProcessEvent(event_button_clicked);
}

void Dialog_Test::OnButtonCancel(wxCommandEvent& WXUNUSED(event)) {
    wxMessageBox(_("TODO: Dialog_Test::OnButtonCancel")); // <---- not executed
    EndModal(wxID_CANCEL);
}

What happens here?

Edit #1: In a wxFrame I use ProcessCommand(wxID_CLOSE_FRAME) in OnClose, but in a wxDialog there is no ProcessCommand.


Solution

  • I think I have found the bug:

    // wrong: don't use ProcessEvent of wxDialog
    // this->ProcessEvent(event_button_clicked);
    
    // right: use ProcessEvent of the custom wxButton
    GetButtonCancel()->GetEventHandler()->ProcessEvent(event_button_clicked);