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 Event
Definition
Occurs directly after Close() is called, and can be handled to cancel window closure.
Event Type
Exceptions
Visibility is set, or Show(), ShowDialog(), or Close() is called while a window is closing.
Examples
The following example demonstrates a Window that determines whether it needs user intervention to close.
Remarks
Closing can be handled to detect when a window is being closed (for example, when Close is called). Furthermore, Closing can be used to prevent a window from closing. To prevent a window from closing, you can set the Cancel property of the CancelEventArgs argument to true .
The Closing event is raised when Close is called, if a window’s Close button is clicked, or if the user presses ALT+F4.
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. If the owner of a window is closed (see Owner), Closing is not raised on the owned window.
If Shutdown is called, the Closing event for each window is raised. However, if Closing is canceled, cancellation is ignored.
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.
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. Then, you can call Show on the same instance to reopen it.
Window. Close Метод
Определение
Вручную закрывает окно Window. Manually closes a Window.
Примеры
В следующем примере показан файл | меню выхода , обрабатываемого для явного вызова Close . The following example shows a File | Exit menu being handled to explicitly call Close.
Комментарии
WindowМожно закрыть с помощью одного из нескольких хорошо известных, предоставляемых системой механизмов, расположенных в его заголовке, в том числе: A Window can be closed using one of several, well-known, system-provided mechanisms located in its title bar, including:
Системное меню | Закрыть. System menu | Close.
Кнопка » Закрыть «. Close button.
WindowТакже можно закрыть с помощью одного из нескольких хорошо известных механизмов в клиентской области, предоставляемых разработчиками, включая: A Window can also be closed using one of several well-known mechanisms within the client area that are provided by developers, including:
Файл | выйти из главного окна. File | Exit on a main window.
Файл | Закрыть или кнопку Закрыть в дочернем окне. File | Close or a Close button on a child window.
Кнопки ОК и Отмена в диалоговом окне также предоставляются разработчиками, хотя, скорее всего, будет установлено DialogResult , которое автоматически закроет окно, открытое при вызове ShowDialog . OK and Cancel buttons on a dialog box are also developer-provided, although will likely set DialogResult, which automatically closes a window that was opened by calling ShowDialog.
Эти механизмы потребовали явного вызова Close для закрытия окна. These mechanisms require you to explicitly call Close to close a window.
Если окно, открытое путем вызова ShowDialog , и со Button IsCancel свойством, для которого задано значение true, автоматически закроется при нажатии кнопки, или если нажать клавишу ESC. If a window, opened by calling ShowDialog, and with a Button with its IsCancel property set to true, will automatically close when the button is either clicked, or ESC is pressed. Если окно было открыто с помощью Show , Close необходимо явно вызвать метод, например из Click обработчика событий для Button . If the window was opened using Show, however, Close must be explicitly called, such as from Click event handler for the Button.
Закрытие окна приводит к Closing возникновению события. Closing a window causes the Closing event to be raised. Если Closing событие не отменено, происходит следующее: If the Closing event isn’t canceled, the following occurs:
WindowУдаляется из Application.Windows (если Application объект существует). The Window is removed from Application.Windows (if an Application object exists).
WindowУдаляется из владельца, Window если отношение владельца и владелец было установлено до того, как Window было отображено и после открытия владельца Window . The Window is removed from the owner Window if the owner/owned relationship was established before the owned Window was shown and after the owner Window was opened.
Возникает событие Closed. The Closed event is raised.
Неуправляемые ресурсы, созданные объектом, Window уничтожаются. Unmanaged resources created by the Window are disposed.
Если ShowDialog был вызван для отображения Window , ShowDialog возвращает. If ShowDialog was called to show the Window, ShowDialog returns.
При закрытии Window вызывается закрытие всех окон, которыми он владеет. Closing a Window causes any windows that it owns to be closed. Кроме того, закрытие Window может привести к прекращению работы приложения в зависимости от того, как Application.ShutdownMode это свойство задано. Furthermore, closing a Window may cause an application to stop running depending on how the Application.ShutdownMode property is set.
Этот метод не может быть вызван, если окно размещается в браузере. This method cannot be called when a window is hosted in a browser.
Window. Close Method
Definition
Manually closes a Window.
Examples
The following example shows a File | Exit menu being handled to explicitly call Close.
Remarks
A Window can be closed using one of several, well-known, system-provided mechanisms located in its title bar, including:
System menu | Close.
Close button.
A Window can also be closed using one of several well-known mechanisms within the client area that are provided by developers, including:
File | Exit on a main window.
File | Close or a Close button on a child window.
OK and Cancel buttons on a dialog box are also developer-provided, although will likely set DialogResult, which automatically closes a window that was opened by calling ShowDialog.
These mechanisms require you to explicitly call Close to close a window.
If a window, opened by calling ShowDialog, and with a Button with its IsCancel property set to true, will automatically close when the button is either clicked, or ESC is pressed. If the window was opened using Show, however, Close must be explicitly called, such as from Click event handler for the Button.
Closing a window causes the Closing event to be raised. If the Closing event isn’t canceled, the following occurs:
The Window is removed from Application.Windows (if an Application object exists).
The Window is removed from the owner Window if the owner/owned relationship was established before the owned Window was shown and after the owner Window was opened.
The Closed event is raised.
Unmanaged resources created by the Window are disposed.
If ShowDialog was called to show the Window, ShowDialog returns.
Closing a Window causes any windows that it owns to be closed. Furthermore, closing a Window may cause an application to stop running depending on how the Application.ShutdownMode property is set.
This method cannot be called when a window is hosted in a browser.
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.