Windows application close event

Application. Application Exit Event

Definition

Occurs when the application is about to shut down.

Event Type

Examples

The following code example displays two forms and exits the application when both forms are closed. When the application starts and exits, the position of each form is remembered. This example demonstrates using the ApplicationExit event to know when the form positions should be persisted to the file, and when the FileStream should be closed.

The class MyApplicationContext inherits from ApplicationContext and keeps track of when each form is closed, and exits the current thread when they both are. The class remembers the position of each form when it is closed. When the ApplicationExit event occurs, the class writes the positions of each for the user to the file. The form position data is stored in a file titled appdata.txt that is created in the location determined by UserAppDataPath. The Main method calls Application.Run(context) to start the application given the ApplicationContext.

This code is an excerpt from the example shown in the ApplicationContext class overview. See ApplicationContext for the whole code listing.

Remarks

You must attach the event handlers to the ApplicationExit event to perform unhandled, required tasks before the application stops running. You can close files opened by this application, or dispose of objects that garbage collection did not reclaim.

Because this is a static event, you must detach any event handlers attached to this event in the ApplicationExit event handler itself. If you do not detach these handlers, they will remain attached to the event and continue to consume memory.

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.

Читайте также:  Windows image backup windows 2012

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.

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.

Читайте также:  Как удалить общий доступ windows 10

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.

Читайте также:  Как понять реестр windows

При 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.

.NET Console Application Exit Event

In .NET, is there a method, such as an event, for detecting when a Console Application is exiting? I need to clean up some threads and COM objects.

I am running a message loop, without a form, from the console application. A DCOM component that I am using seems to require that the application pump messages.

I have tried adding a handler to Process.GetCurrentProcess.Exited and Process.GetCurrentProcess.Disposed.

I have also tried adding a handler to Application.ApplicationExit and Application.ThreadExit events, but they are not firing. Perhaps that is because I am not using a form.

6 Answers 6

You can use the ProcessExit event of the AppDomain :

Update

Here is a full example program with an empty «message pump» running on a separate thread, that allows the user to input a quit command in the console to close down the application gracefully. After the loop in MessagePump you will probably want to clean up resources used by the thread in a nice manner. It’s better to do that there than in ProcessExit for several reasons:

  • Avoid cross-threading problems; if external COM objects were created on the MessagePump thread, it’s easier to deal with them there.
  • There is a time limit on ProcessExit (3 seconds by default), so if cleaning up is time consuming, it may fail if pefromed within that event handler.
Оцените статью