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.
Form. Close Метод
Определение
Закрывает форму. Closes the form.
Исключения
Форма была закрыта при создании дескриптора. The form was closed while a handle was being created.
Нельзя вызывать этот метод из события Activated, если свойство WindowState задано как Maximized. You cannot call this method from the Activated event when WindowState is set to Maximized.
Комментарии
При закрытии формы все ресурсы, созданные в объекте, закрываются, и форма удаляется. When a form is closed, all resources created within the object are closed and the form is disposed. Можно предотвратить закрытие формы во время выполнения, обрабатывая Closing событие и установив Cancel свойство объекта, CancelEventArgs переданного в качестве параметра обработчику событий. You can prevent the closing of a form at run time by handling the Closing event and setting the Cancel property of the CancelEventArgs passed as a parameter to your event handler. Если закрываемая форма является начальной формой приложения, приложение завершается. If the form you are closing is the startup form of your application, your application ends.
Два условия, когда форма не удаляется Close , имеет значение, если (1) она является частью приложения с многодокументным интерфейсом (MDI), а форма не видна, и (2) форма была отображена с помощью ShowDialog . The two conditions when a form is not disposed on Close is when (1) it is part of a multiple-document interface (MDI) application, and the form is not visible; and (2) you have displayed the form using ShowDialog. В таких случаях необходимо вручную вызвать, Dispose чтобы пометить все элементы управления формы для сборки мусора. In these cases, you will need to call Dispose manually to mark all of the form’s controls for garbage collection.
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.
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).
c# open a new form then close the current form?
For example, Assume that I’m in form 1 then I want:
- Open form 2( from a button in form 1)
- Close form 1
- Focus on form 2
15 Answers 15
Steve’s solution does not work. When calling this.Close(), current form is disposed together with form2. Therefore you need to hide it and set form2.Closed event to call this.Close().
Many different ways have already been described by the other answers. However, many of them either involved ShowDialog() or that form1 stay open but hidden. The best and most intuitive way in my opinion is to simply close form1 and then create form2 from an outside location (i.e. not from within either of those forms). In the case where form1 was created in Main , form2 can simply be created using Application.Run just like form1 before. Here’s an example scenario:
I need the user to enter their credentials in order for me to authenticate them somehow. Afterwards, if authentication was successful, I want to show the main application to the user. In order to accomplish this, I’m using two forms: LogingForm and MainForm . The LoginForm has a flag that determines whether authentication was successful or not. This flag is then used to decide whether to create the MainForm instance or not. Neither of these forms need to know about the other and both forms can be opened and closed gracefully. Here’s the code for this: