2.2.9 Terminating an Application

Your application terminates when the WinMain function returns control to Windows. WinMain can return control at any time before starting the message loop. Typically, an application checks each step leading up to the message loop to make sure each window class is registered and each window is created. If there is an error, the application can display a message before terminating.

Once the WinMain function enters the message loop, however, the only way to terminate the loop is to post a WM_QUIT message in the application queue by using the PostQuitMessage function. When the GetMessage function retrieves a WM_QUIT message, it returns NULL, which terminates the message loop. Typically, the window procedure for the application's main window posts a WM_QUIT message when the main window is being destroyed (that is, when the window procedure has received a WM_DESTROY message).

Although WinMain specifies a data type for its return value, Windows does not currently use the return value. For debugging an application, however, a return value can be helpful. In general, the easiest return-code conventions are those used by standard C-language applications: zero for successful execution, nonzero for error. The PostQuitMessage function lets the window procedure specify the return value. This value is then copied to the wParam parameter of the WM_QUIT message. To return this value after terminating the message loop, use the following statement:

return (msg.wParam);   /* returns value from PostQuitMessage */

Although standard C-language applications typically free any allocated resources just prior to terminating, Windows applications should free resources as each window is destroyed. This process is called “cleaning up.” Failing to clean up can cause an application to lose some data. For example, when Windows itself terminates, it destroys each window but does not return control to the application's message loop. This means that the loop never retrieves the WM_QUIT message and the statements after the loop are not executed. (Windows does send each application a WM_QUERYENDSESSION message before terminating, so an application does have an opportunity to carry out tasks before terminating. For more information about the WM_QUERYENDSESSION message, see Chapter 10, “File Input and Output.”