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.
Closing Applications
What is best practice when closing a C# application?
I have read that you can use:
But what is the difference?
Furthermore, with regards to Environment.Exit(0), I have used exit codes before when working with Java but have never fully understood their purpose. What role do they play when exiting an application in C#?
4 Answers 4
System.Windows.Forms.Application.Exit() — Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit() method is typically called from within a message loop, and forces Run() to return. To exit a message loop for the current thread only, call ExitThread() . This is the call to use if you are running a Windows Forms application. As a general guideline, use this call if you have called System.Windows.Forms.Application.Run() .
System.Environment.Exit(exitCode) — Terminates this process and gives the underlying operating system the specified exit code. This call requires that you have SecurityPermissionFlag.UnmanagedCode permissions. If you do not, a SecurityException error occurs. This is the call to use if you are running a console application.
I hope it is best to use Application.Exit
See also these links:
Application.Exit is for Windows Forms applications — it informs all message pumps that they should terminate, waits for them to finish processing events and then terminates the application. Note that it doesn’t necessarily force the application to exit.
Environment.Exit is applicable for all Windows applications, however it is mainly intended for use in console applications. It immediately terminates the process with the given exit code.
In general you should use Application.Exit in Windows Forms applications and Environment.Exit in console applications, (although I prefer to let the Main method / entry point run to completion rather than call Environment.Exit in console applications).
For more detail see the MSDN documentation.
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:
Application. Exit Метод
Определение
Сообщает всем средствам переноса сообщений, что они должны завершить работу, а затем закрывает все окна приложения после обработки сообщений. Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.
Перегрузки
Сообщает всем средствам переноса сообщений, что они должны завершить работу, а затем закрывает все окна приложения после обработки сообщений. Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.
Сообщает всем средствам переноса сообщений, что они должны завершить работу, а затем закрывает все окна приложения после обработки сообщений. Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.
Сообщает всем средствам переноса сообщений, что они должны завершить работу, а затем закрывает все окна приложения после обработки сообщений. Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.
Примеры
В следующем примере кода показаны числа из списка в форме. The following code example lists numbers in a list box on a form. Каждый раз при щелчке button1 приложение добавляет в список еще один номер. Each time you click button1 , the application adds another number to the list.
Main Метод вызывает, Run чтобы запустить приложение, которое создает форму, listBox1 и button1 . The Main method calls Run to start the application, which creates the form, listBox1 , and button1 . Когда пользователь нажимает кнопку button1 , button1_Click метод добавляет числа от 1 до 3 в список и отображает MessageBox . When the user clicks button1 , the button1_Click method adds numbers one to three to the list box, and displays a MessageBox. Если пользователь нажимает кнопку нет в MessageBox , button1_Click метод добавляет еще один номер в список. If the user clicks No on the MessageBox, the button1_Click method adds another number to the list. Если пользователь нажмет кнопку Да, приложение вызывает Exit , чтобы обработать все оставшиеся сообщения в очереди и затем завершить работу. If the user clicks Yes, the application calls Exit, to process all remaining messages in the queue and then to quit.
Для примера требуется, чтобы listBox1 и button1 были созданы и помещены в форму. The example requires that listBox1 and button1 have been instantiated and placed on a form.
Комментарии
ExitМетод останавливает все выполняющиеся циклы сообщений во всех потоках и закрывает все окна приложения. The Exit method stops all running message loops on all threads and closes all windows of the application. Этот метод не обязательно приводит к принудительному завершению работы приложения. This method does not necessarily force the application to exit. ExitМетод обычно вызывается из цикла обработки сообщений и принудительно Run возвращает значение. The Exit method is typically called from within a message loop, and forces Run to return. Чтобы выйти из цикла обработки сообщений только для текущего потока, вызовите ExitThread . To exit a message loop for the current thread only, call ExitThread.
Exit вызывает следующие события и выполняет связанные условные действия: Exit raises the following events and performs the associated conditional actions:
FormClosingСобытие вызывается для каждой формы, представленной OpenForms свойством. A FormClosing event is raised for every form represented by the OpenForms property. Это событие можно отменить, задав Cancel для свойства своего параметра значение FormClosingEventArgs true . This event can be canceled by setting the Cancel property of their FormClosingEventArgs parameter to true .
Если один из обработчиков отменяет событие, а Exit возвращает без дальнейших действий. If one of more of the handlers cancels the event, then Exit returns without further action. В противном случае FormClosed событие вызывается для каждой открытой формы, после чего все выполняющиеся циклы сообщений и формы закрываются. Otherwise, a FormClosed event is raised for every open form, then all running message loops and forms are closed.
ExitМетод не вызывает Closed Closing события и, которые устарели в платформа .NET Framework 2,0. The Exit method does not raise the Closed and Closing events, which are obsolete as of .NET Framework 2.0.