Terminating an Application

Your application terminates when the WinMain function returns control to Windows. You 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 function for the application's main window posts a WM_QUIT message when the main window is being destroyed (that is, when the window function has received a WM_DESTROY message).

Although WinMain specifies a data type for its return value, Windows does not currently use the return value. While you are debugging an application, however, a return value can be helpful. In general, you might use the same return-code conventions that standard C programs use: zero for successful execution, nonzero for error. The PostQuitMessage function lets the window function specify the return value. This value is then copied to the wParam parameter of the WM_QUITmessage. To return this value after terminating the message loop, use the following statement:

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

Although standard C programs typically clean up and free resources just prior to termination, Windows applications should clean up as each window is destroyed. If you do not clean up as each window is destroyed, you 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 message before terminating, so an application does have an opportunity to carry out tasks before terminating. For an illustration of the WM_QUERYENDSESSION message, see Chapter 22, “File Input and Output.”)