Επεξεργασία

Κοινή χρήση μέσω


Closing the Window

When the user closes a window, that action triggers a sequence of window messages.

The user can close an application window by clicking the Close button, or by using a keyboard shortcut such as ALT+F4. Any of these actions causes the window to receive a WM_CLOSE message. The WM_CLOSE message gives you an opportunity to prompt the user before closing the window. If you really do want to close the window, call the DestroyWindow function. Otherwise, simply return zero from the WM_CLOSE message, and the operating system will ignore the message and not destroy the window.

Here is an example of how a program might handle WM_CLOSE.

case WM_CLOSE:
    if (MessageBox(hwnd, L"Really quit?", L"My application", MB_OKCANCEL) == IDOK)
    {
        DestroyWindow(hwnd);
    }
    // Else: User canceled. Do nothing.
    return 0;

In this example, the MessageBox function shows a modal dialog that contains OK and Cancel buttons. If the user clicks OK, the program calls DestroyWindow. Otherwise, if the user clicks Cancel, the call to DestroyWindow is skipped, and the window remains open. In either case, return zero to indicate that you handled the message.

If you want to close the window without prompting the user, you could simply call DestroyWindow without the call to MessageBox. However, there is a shortcut in this case. Recall that DefWindowProc executes the default action for any window message. In the case of WM_CLOSE, DefWindowProc automatically calls DestroyWindow. That means if you ignore the WM_CLOSE message in your switch statement, the window is destroyed by default.

When a window is about to be destroyed, it receives a WM_DESTROY message. This message is sent after the window is removed from the screen, but before the destruction occurs (in particular, before any child windows are destroyed).

In your main application window, you will typically respond to WM_DESTROY by calling PostQuitMessage.

case WM_DESTROY:
    PostQuitMessage(0);
    return 0;

We saw in the Window Messages section that PostQuitMessage puts a WM_QUIT message on the message queue, causing the message loop to end.

Here is a flow chart showing the typical way to process WM_CLOSE and WM_DESTROY messages:

flow chart showing how to handle wm-close and wm-destroy messages

Next

Managing Application State