Event when application is about to be shut down in wxWidgets

Viewed 48

My application uses the docview framework provided by wxWidgets. In the OnClose() method of my wxView-derived class I have to know whether only this single window is about to be closed or the whole application gets shut down. (I have to do some housekeeping work before all the windows get closed.)

Is there any event being fired when the application is exiting, before the views are getting closed?

I tried to set a flag in wxApp::OnExit(), but OnExit() is called only after all the windows have been closed already, so this doesn't work.

Update for some clarification: I don't want to know who initiated the closing of the application. I need to find out in wxView::OnClose() if the user just closes this single window or the application as a whole.

2 Answers

The application can be closed either explicitly by your program or implicitly because the main window is closed by the user. In the latter case you're going to get wxEVT_CLOSE_WINDOW, so you could catch it and do whatever you need to do there -- e.g. this is commonly used to propose to save the changes before closing.

I ended up with a solution that's possibly a workaround, but seems to work well, at least on macOS. I override FilterEvent() in my wxApp-derived class:

int MyApp::FilterEvent(wxEvent& event) {
    const wxEventType evt_type = event.GetEventType();
    const int evt_id = event.GetId();
    if( evt_type == wxEVT_MENU && evt_id == wxID_EXIT ) {
        m_about_to_quit = true;
    }
}

No matter if the user clicks "Appname Menu > Quit Appname" or uses the shortcut CMD+q, the if clause is true and the flag is set.

Depending on the state of m_about_to_quit, I can now distinguish in wxView::OnClose() if only this view is closed or the application is about to be shut down and do my housekeeping if necessary.

Note: Using SDI GUI mode, the main frame is shown (at least on macOS). If the user closes that main frame, the application shuts down without setting m_about_to_quit to true. In this case, you'd need to set m_about_to_quit in the OnClose event of the main frame, too.

Related