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.
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.
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:
Window. Closing Событие
Определение
Происходит непосредственно после вызова метода Close() и может быть обработано с отменой закрытия окна. Occurs directly after Close() is called, and can be handled to cancel window closure.
Тип события
Исключения
Задано свойство Visibility либо вызван один из методов Show(), ShowDialog() или Close() во время закрытия окна. Visibility is set, or Show(), ShowDialog(), or Close() is called while a window is closing.
Примеры
В следующем примере демонстрируется Window , что определяет, требуется ли для закрытия вмешательство пользователя. The following example demonstrates a Window that determines whether it needs user intervention to close.
Комментарии
Closing может обрабатываться для обнаружения закрытия окна (например, при Close вызове). Closing can be handled to detect when a window is being closed (for example, when Close is called). Кроме того, Closing можно использовать, чтобы предотвратить закрытие окна. Furthermore, Closing can be used to prevent a window from closing. Чтобы предотвратить закрытие окна, можно присвоить Cancel свойству CancelEventArgs аргумента значение true . To prevent a window from closing, you can set the Cancel property of the CancelEventArgs argument to true .
ClosingСобытие возникает при Close вызове, если нажата кнопка закрытия окна или если пользователь нажмет Alt + F4. The Closing event is raised when Close is called, if a window’s Close button is clicked, or if the user presses ALT+F4.
Если принадлежащее окно было открыто окном-владельцем с помощью Show , а окно владельца закрыто, событие принадлежащего окна Closing не вызывается. If an owned window was opened by its owner window using Show, and the owner window is closed, the owned window’s Closing event is not raised. Если владелец окна закрыт (см Owner . раздел), Closing в принадлежащем окне не создается. If the owner of a window is closed (see Owner), Closing is not raised on the owned window.
При Shutdown вызове метода вызывается Closing событие для каждого окна. If Shutdown is called, the Closing event for each window is raised. Однако если операция Closing отменена, то отмена игнорируется. However, if Closing is canceled, cancellation is ignored.
Значение, если сеанс завершается из-за того, что пользователь выходит из системы или завершает работу, Closing не вызывается; обрабатывается SessionEnding для реализации кода, который отменяет закрытие приложения. If a session ends because a user logs off or shuts down, Closing is not raised; handle SessionEnding to implement code that cancels application closure.
Если вы хотите отображать и скрывать окно несколько раз в течение всего времени существования приложения и вы не хотите повторно создавать экземпляры окна при каждом его отображении, можно обойти Closing событие, отменить его и вызвать Hide метод. If you want to show and hide a window multiple times during the lifetime of an application, and you don’t want to reinstantiate the window each time you show it, you can handle the Closing event, cancel it, and call the Hide method. Затем можно вызвать в Show том же экземпляре, чтобы снова открыть его. Then, you can call Show on the same instance to reopen it.