Microsoft KB Archive/117320

= How to Programatically Terminate an MFC Application =

Article ID: 117320

Article Last Modified on 11/21/2006

-

APPLIES TO

 Microsoft Foundation Class Library 4.2, when used with:  Microsoft Visual C++ 1.0 Professional Edition

 Microsoft Visual C++ 1.5 Professional Edition

 Microsoft Visual C++ 1.51

 Microsoft Visual C++ 1.52 Professional Edition</li></ul>

 Microsoft Visual C++ 1.0 Professional Edition</li></ul>

 Microsoft Visual C++ 2.0 Professional Edition</li></ul>

 Microsoft Visual C++ 2.1</li></ul>

 Microsoft Visual C++ 4.0 Standard Edition</li></ul> </li></ul>

-

<div class="notice_section">

This article was previously published under Q117320

<div class="summary_section">

SUMMARY
Under certain conditions, you may want to terminate an MFC application programatically. MFC does not provide a public function to gracefully exit an application.

<div class="moreinformation_section">

MORE INFORMATION
A method for dealing with this is to create a function in your application like the following: void ExitApp {       // same as double-clicking on main window close box ASSERT(AfxGetApp->m_pMainWnd != NULL); AfxGetApp->m_pMainWnd->SendMessage(WM_CLOSE); } As you can see, this is implemented as a global function, which can be called from anywhere in your application. It simply sends a WM_CLOSE message to your application's mainframe window. This initiates an orderly shutdown of the application.

If you are using MFC, version 2.5 or later, you can take advantage of a new global MFC function, "AfxGetMainWnd", to simplify the code: void ExitMFCApp {       // same as double-clicking on main window close box ASSERT(AfxGetMainWnd != NULL); AfxGetMainWnd->SendMessage(WM_CLOSE); } NOTE: Always call CDocument::SetModifiedFlag after changing your document data. This will ensure that the framework prompts the user to save before shutdown. If you need more extensive control over the shutdown procedure, you can override CDocument::SaveModified.

Additional query words: kbinf 1.00 1.50 1.51 1.52 2.00 2.10 2.50 2.51 2.52 3.00 3.10 4.00

Keywords: KB117320

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.