How can an MFC application terminate itself?
-
08-06-2019 - |
Question
What is the proper way for an MFC application to cleanly close itself?
Solution
Programatically Terminate an MFC Application
void ExitMFCApp()
{
// same as double-clicking on main window close box
ASSERT(AfxGetMainWnd() != NULL);
AfxGetMainWnd()->SendMessage(WM_CLOSE);
}
OTHER TIPS
AfxGetMainWnd()->PostMessage(WM_CLOSE);
In support of @Mike's answer, the reason to use this method is to trigger the correct shutdown sequence. Especially important for MDI/SDI applications because it gives a chance for documents to prompt for save before exit or to cancel the exit.
@Matt Noguchi, your method will circumvent this sequence (which may be the desired effect, I suppose, but you've probably got problems if you're short-circuiting the normal teardown.
PostQuitMessage( [exit code] );
If it is a dialog based application you can do it by calling EndDialog() function.
If it is an SDI/MDI based application you can call DestroyWindow. But before which you will need to do the cleanup yourself (closing documents, deallocating memory and resources, destroying any additional windows created etc).