What is the correct way to programmatically quit an MFC application?

人走茶凉 提交于 2019-11-28 09:46:42

In InitInstance()

Exiting the app while you are still in InitInstance(): Simply return FALSE from InitInstance().

In the main message loop

It's another story though if you are already in the message loop: The standard way to close an app is to exit the message loop:

PostQuitMessage(0), as its name implies, posts a WM_QUIT message. The message loop reacts by exiting the loop and closing the program.

But you shouldn't simply do that: You should close the opened windows in your app. Assuming you have only your main window, you should destroy it by calling

m_pMainWindow->DestroyWindow();

MFC will react by PostQuitMessage() for you, hence exit the main message loop and close your app.

Better yet, you should post a WM_CLOSE to let your main window close gracefully. It may for example decide to save the current document. Beware though: the standard OnClose() handler may prompt user to save dirty documents. User can even cancel the close action using this prompt (Save document? Yes, No, Cancel).

Destroying the main window will post a WM_DESTROY message to it. MFC reacts by calling PostQuitMessage(0) to exit the message pump. (Actually, MFC does the call in OnNcDestroy() since WM_NCDESTROY which is the absolute last mesage received by a window)

Dialog-based app

Call EndDialog(-1); // Or replace -1 by IDCANCEL, whatever

This call, as you probably know, will close the dialog.

Note that the main dialog of dialog-based app executes in InitInstance(). Closing the dialog will simply exit InitInstance(), which always returns FALSE in such projects.

Simply use:

PostQuitMessage(0);

Keep in mind your program won't quit instantly from this call, the window/program will receive a WM_QUIT message and then your program will quit.

Serge - your answer is unfortunately not the best way to do it. PostQuitMessage(0) is the way to go and MFC will destroy the windows for you. You should avoid calling m_pMainWindow->DestroyWindow() directly.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!