我的应用程序使用
wxWidgets提供的
docview
框架。在我的 OnClose()
派生类的 wxView
方法中,我必须知道是否只有这个单个窗口即将关闭,或者整个应用程序将被关闭。 (在所有窗户关闭之前我必须做一些家务工作。)
应用程序退出时、视图关闭之前是否会触发任何事件?
我尝试在
wxApp::OnExit()
中设置一个标志,但是 OnExit()
仅在所有窗口都已关闭后才会被调用,所以这不起作用。
更新一些澄清:我不想知道谁发起了应用程序的关闭。我需要在
wxView::OnClose()
中找出用户是否只是关闭这个单个窗口或整个应用程序。
我最终得到了一个可能是解决方法的解决方案,但似乎效果很好,至少在 macOS 上是这样。我在
FilterEvent()
派生类中重写 wxApp
:
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;
}
}
无论用户点击“Appname菜单>退出Appname”还是使用快捷键CMD+q,
if
子句都是true
并且设置标志。
根据
m_about_to_quit
的状态,我现在可以在 wxView::OnClose()
中区分是否仅关闭此视图或应用程序即将关闭,并在必要时进行内务处理。
注意:使用SDI GUI模式,显示主框架(至少在macOS上)。如果用户关闭该主框架,应用程序将关闭,而不将
m_about_to_quit
设置为 true
。在这种情况下,您还需要在主框架的 m_about_to_quit
事件中设置 OnClose
。
应用程序可以由程序显式关闭,也可以因为主窗口由用户关闭而隐式关闭。在后一种情况下,您将得到
wxEVT_CLOSE_WINDOW
,因此您可以抓住它并在那里做任何您需要做的事情 - 例如这通常用于建议在关闭之前保存更改。
wxAppConsole::OnExit
应该完成这项工作:
class MyApp : public wxApp {
public:
//...
virtual int OnExit();
//...
};
int MyApp::OnExit() {
// Perform cleanup or any actions before the application exits
//...
// Returning 0 indicates a normal exit, you can return a different value if needed
return 0;
}