- Form. Closed Event
- Definition
- Event Type
- Examples
- Remarks
- Form. Closing Event
- Definition
- Event Type
- Examples
- Remarks
- Window. Closing Событие
- Определение
- Тип события
- Исключения
- Примеры
- Комментарии
- Form. Closed Событие
- Определение
- Тип события
- Примеры
- Комментарии
- Порядок событий в формах Windows Forms Order of Events in Windows Forms
- События запуска и завершения работы приложения Application Startup and Shutdown Events
- События, связанные с фокусом и проверками Focus and Validation Events
Form. Closed Event
Definition
Occurs when the form is closed.
Event Type
Examples
The following example demonstrates how to use the SetDesktopLocation, Closed, Load, Activated, and Activate members. To run the example, paste the following code in a form called Form1 containing a Button called Button1 and two Label controls called Label1 and Label2 .
Remarks
The Closed event is obsolete in the .NET Framework version 2.0; use the FormClosed event instead.
This event occurs after the form has been closed by the user or by the Close method of the form. To prevent a form from closing, handle the Closing event and set the Cancel property of the CancelEventArgs passed to your event handler to true .
You can use this event to perform tasks such as freeing resources used by the form and to save information entered in the form or to update its parent form.
The Form.Closed and Form.Closing events are not raised when the Application.Exit method is called to exit your application. If you have validation code in either of these events that must be executed, you should call the Form.Close method for each open form individually before calling the Exit method.
If the form is an MDI parent form, the Closing events of all MDI child forms are raised before the MDI parent form’s Closing event is raised. In addition, the Closed events of all MDI child forms are raised before the Closed event of the MDI parent form is raised.
For more information about handling events, see Handling and Raising Events.
Form. Closing Event
Definition
Occurs when the form is closing.
Event Type
Examples
The following example uses Closing to test if the text in a TextBox has changed. If it has, the user is asked whether to save the changes to a file.
Remarks
The Closing event is obsolete starting with the .NET Framework 2.0; use the FormClosing event instead.
The Closing event occurs as the form is being closed. When a form is closed, all resources created within the object are released and the form is disposed. If you cancel this event, the form remains opened. To cancel the closure of a form, set the Cancel property of the CancelEventArgs passed to your event handler to true .
When a form is displayed as a modal dialog box, clicking the Close button (the button with an X at the upper-right corner of the form) causes the form to be hidden and the DialogResult property to be set to DialogResult.Cancel . You can override the value assigned to the DialogResult property when the user clicks the Close button by setting the DialogResult property in an event handler for the Closing event of the form.
When the Close method is called on a Form displayed as a modeless window, you cannot call the Show method to make the form visible, because the form’s resources have already been released. To hide a form and then make it visible, use the Control.Hide method.
The Form.Closed and Form.Closing events are not raised when the Application.Exit method is called to exit your application. If you have validation code in either of these events that must be executed, you should call the Form.Close method for each open form individually before calling the Exit method.
If the form is an MDI parent form, the Closing events of all MDI child forms are raised before the MDI parent form’s Closing event is raised. In addition, the Closed events of all MDI child forms are raised before the Closed event of the MDI parent form is raised. Canceling the Closing event of an MDI child form does not prevent the Closing event of the MDI parent form from being raised. However, canceling the event will set to true the Cancel property of the CancelEventArgs that is passed as a parameter to the parent form. To force all MDI parent and child forms to close, set the Cancel property to false in the MDI parent form.
For more information about handling events, see Handling and Raising Events.
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.
Form. Closed Событие
Определение
Происходит при закрытой форме. Occurs when the form is closed.
Тип события
Примеры
В следующем примере показано, как использовать SetDesktopLocation элементы, Closed , Load , Activated и Activate . The following example demonstrates how to use the SetDesktopLocation, Closed, Load, Activated, and Activate members. Чтобы выполнить пример, вставьте следующий код в форму с именем, Form1 которая содержит Button вызываемый метод Button1 , и два Label элемента управления с именем Label1 и Label2 . To run the example, paste the following code in a form called Form1 containing a Button called Button1 and two Label controls called Label1 and Label2 .
Комментарии
ClosedСобытие является устаревшим в платформа .NET Framework версии 2,0; используйте FormClosed событие. The Closed event is obsolete in the .NET Framework version 2.0; use the FormClosed event instead.
Это событие происходит после закрытия формы пользователем или Close методом формы. This event occurs after the form has been closed by the user or by the Close method of the form. Чтобы предотвратить закрытие формы, обработайте Closing событие и задайте Cancel для свойства объекта, CancelEventArgs переданного обработчику событий, значение true . To prevent a form from closing, handle the Closing event and set the Cancel property of the CancelEventArgs passed to your event handler to true .
Это событие можно использовать для выполнения таких задач, как освобождение ресурсов, используемых формой, и сохранения информации, введенной в форму, или для обновления ее родительской формы. You can use this event to perform tasks such as freeing resources used by the form and to save information entered in the form or to update its parent form.
Form.ClosedСобытия и Form.Closing не вызываются при Application.Exit вызове метода для выхода из приложения. The Form.Closed and Form.Closing events are not raised when the Application.Exit method is called to exit your application. При наличии кода проверки в любом из этих событий, которые необходимо выполнить, следует вызывать Form.Close метод для каждой открытой формы по отдельности перед вызовом Exit метода. If you have validation code in either of these events that must be executed, you should call the Form.Close method for each open form individually before calling the Exit method.
Если форма является родительской MDI-формой, то Closing события всех дочерних форм MDI создаются до возникновения события родительской формы MDI Closing . If the form is an MDI parent form, the Closing events of all MDI child forms are raised before the MDI parent form’s Closing event is raised. Кроме того, Closed события всех дочерних форм MDI вызываются до того, как Closed будет вызвано событие родительской формы MDI. In addition, the Closed events of all MDI child forms are raised before the Closed event of the MDI parent form is raised.
Дополнительные сведения об обработке событий см. в разделе обработка и вызов событий. For more information about handling events, see Handling and Raising Events.
Порядок событий в формах Windows Forms Order of Events in Windows Forms
Особый интерес для разработчиков представляет порядок, в котором вызываются события в приложениях Windows Forms, для обеспечения обработки каждого из этих событий в свою очередь. The order in which events are raised in Windows Forms applications is of particular interest to developers concerned with handling each of these events in turn. Если ситуация требует аккуратной обработки событий, например когда производится перерисовка части формы, то необходимо знать точный порядок, в котором вызываются события во время выполнения. When a situation calls for meticulous handling of events, such as when you are redrawing parts of the form, an awareness of the precise order in which events are raised at run time is necessary. В этом разделе приведены некоторые сведения о порядке событий, возникающих на нескольких важных этапах жизненного цикла приложений и элементов управления. This topic provides some details on the order of events during several important stages in the lifetime of applications and controls. Конкретные сведения о порядке событий ввода мыши см. в разделе события мыши в Windows Forms. For specific details about the order of mouse input events, see Mouse Events in Windows Forms. Общие сведения о событиях в Windows Forms см. в разделе Общие сведения о событиях. For an overview of events in Windows Forms, see Events Overview. Дополнительные сведения о описывающего обработчиков событий см. в разделе Общие сведения об обработчиках событий. For details about the makeup of event handlers, see Event Handlers Overview.
События запуска и завершения работы приложения Application Startup and Shutdown Events
Классы Form и Control предоставляют набор событий, связанных с запуском и завершением приложения. The Form and Control classes expose a set of events related to application startup and shutdown. При запуске приложения Windows Forms события запуска главной формы вызываются в следующем порядке: When a Windows Forms application starts, the startup events of the main form are raised in the following order:
При закрытии приложения события запуска главной формы вызываются в следующем порядке: When an application closes, the shutdown events of the main form are raised in the following order:
Событие ApplicationExit класса Application вызывается после событий завершения работы основной формы. The ApplicationExit event of the Application class is raised after the shutdown events of the main form.
В Visual Basic 2005 содержатся дополнительные события приложений, такие как WindowsFormsApplicationBase.Startup и WindowsFormsApplicationBase.Shutdown. Visual Basic 2005 includes additional application events, such as WindowsFormsApplicationBase.Startup and WindowsFormsApplicationBase.Shutdown.
События, связанные с фокусом и проверками Focus and Validation Events
При изменении фокуса с помощью клавиатуры (при нажатии клавиш TAB, SHIFT+TAB и так далее), путем вызова методов Select или SelectNextControl, либо присвоением свойства ActiveControl текущей форме, события фокуса ввода класса Control происходят в следующем порядке: When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ActiveControl property to the current form, focus events of the Control class occur in the following order:
При изменении фокуса ввода с помощью мыши или путем вызова метода Focus события фокуса класса Control происходят в следующем порядке. When you change the focus by using the mouse or by calling the Focus method, focus events of the Control class occur in the following order: