Windows forms close window event

Порядок событий в формах 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:

Form. Closing Событие

Определение

Происходит при закрытии формы. Occurs when the form is closing.

Тип события

Примеры

В следующем примере используется Closing для проверки, изменился ли текст в TextBox . 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.

Читайте также:  Application windows phone android

Комментарии

ClosingСобытие является устаревшим, начиная с платформа .NET Framework 2,0; FormClosing вместо этого используйте событие. The Closing event is obsolete starting with the .NET Framework 2.0; use the FormClosing event instead.

Это Closing событие возникает при закрытии формы. 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. Чтобы отменить закрытие формы, задайте для Cancel свойства объекта, CancelEventArgs переданного обработчику событий, значение true . To cancel the closure of a form, set the Cancel property of the CancelEventArgs passed to your event handler to true .

Когда форма отображается как модальное диалоговое окно, нажатие кнопки Закрыть (кнопка с крестиком в правом верхнем углу формы) приводит к скрытию формы и свойству, для которого DialogResult устанавливается значение DialogResult.Cancel . 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 . Можно переопределить значение, присваиваемое DialogResult свойству, когда пользователь нажимает кнопку Закрыть , задавая DialogResult свойство в обработчике событий для события в Closing форме. 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.

При Close вызове метода для, Form отображаемого в виде немодального окна, нельзя вызвать Show метод, чтобы сделать форму видимой, поскольку ресурсы формы уже были освобождены. 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. Чтобы скрыть форму и сделать ее видимой, используйте Control.Hide метод. To hide a form and then make it visible, use the Control.Hide method.

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. Отмена Closing события дочерней формы MDI не мешает Closing порождению события РОДИТЕЛЬСКОй MDI-формы. Canceling the Closing event of an MDI child form does not prevent the Closing event of the MDI parent form from being raised. Однако при отмене события будет задано true Cancel свойство объекта CancelEventArgs , которое передается в качестве параметра родительской форме. However, canceling the event will set to true the Cancel property of the CancelEventArgs that is passed as a parameter to the parent form. Чтобы принудительно закрыть все родительские и дочерние формы MDI, задайте Cancel для свойства значение false в родительской форме MDI. To force all MDI parent and child forms to close, set the Cancel property to false in the MDI parent form.

Читайте также:  Просмотрщик файлов dwg для windows 10

Дополнительные сведения об обработке событий см. в разделе обработка и вызов событий. 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. 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.

Читайте также:  Dvb для mac os

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.

C# Windows Form: On Close Do [Process]

How can I get my windows form to do something when it is closed.

6 Answers 6

Handle the FormClosed event.

To do that, go to the Events tab in the Properties window and double-click the FormClosed event to add a handler for it.

You can then put your code in the generated MyForm_FormClosed handler.

You can also so this by overriding the OnFormClosed method; to do that, type override onformcl in the code window and OnFormClosed from IntelliSense.

If you want to be able to prevent the form from closing, handle the FormClosing event instead, and set e.Cancel to true .

Or another alternative is to override the OnFormClosed() or OnFormClosing() methods from System.Windows.Forms.Form.

Whether you should use this method depends on the context of the problem, and is more usable when the form will be sub classed several times and they all need to perform the same code.

Events are more useful for one or two instances if you’re doing the same thing.

WinForms has two events that you may want to look at.

The first, the FormClosing event, happens before the form is actually closed. In this event, you can still access any controls and variables in the form’s class. You can also cancel the form close by setting e.Cancel = true; (where e is a System.Windows.Forms.FormClosingEventArgs sent as the second argument to FormClosing ).

The second, the FormClosed event, happens after the form is closed. At this point, you can’t access any controls that the form had, although you can still do cleanup on variables (such as Closing managed resources).

Оцените статью