Application.ApplicationExit Event

Definition

Occurs when the application is about to shut down.

public:
 static event EventHandler ^ ApplicationExit;
public static event EventHandler ApplicationExit;
public static event EventHandler? ApplicationExit;
member this.ApplicationExit : EventHandler 
Public Shared Custom Event ApplicationExit As EventHandler 

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.

   MyApplicationContext()
   {
      _formCount = 0;
      
      // Handle the ApplicationExit event to know when the application is exiting.
      Application::ApplicationExit += gcnew EventHandler( this, &MyApplicationContext::OnApplicationExit );
      try
      {
         
         // Create a file that the application will store user specific data in.
         _userData = gcnew FileStream( String::Concat( Application::UserAppDataPath, "\\appdata.txt" ),FileMode::OpenOrCreate );
      }
      catch ( IOException^ e ) 
      {
         
         // Inform the user that an error occurred.
         MessageBox::Show( "An error occurred while attempting to show the application. The error is: {0}", dynamic_cast<String^>(e) );
         
         // Exit the current thread instead of showing the windows.
         ExitThread();
      }

      
      // Create both application forms and handle the Closed event
      // to know when both forms are closed.
      _form1 = gcnew AppForm1;
      _form1->Closed += gcnew EventHandler( this, &MyApplicationContext::OnFormClosed );
      _form1->Closing += gcnew CancelEventHandler( this, &MyApplicationContext::OnFormClosing );
      _formCount++;
      _form2 = gcnew AppForm2;
      _form2->Closed += gcnew EventHandler( this, &MyApplicationContext::OnFormClosed );
      _form2->Closing += gcnew CancelEventHandler( this, &MyApplicationContext::OnFormClosing );
      _formCount++;
      
      // Get the form positions based upon the user specific data.
      if ( ReadFormDataFromFile() )
      {
         
         // If the data was read from the file, set the form
         // positions manually.
         _form1->StartPosition = FormStartPosition::Manual;
         _form2->StartPosition = FormStartPosition::Manual;
         _form1->Bounds = _form1Position;
         _form2->Bounds = _form2Position;
      }

      
      // Show both forms.
      _form1->Show();
      _form2->Show();
   }

   void OnApplicationExit( Object^ /*sender*/, EventArgs^ /*e*/ )
   {
      
      // When the application is exiting, write the application data to the
      // user file and close it.
      WriteFormDataToFile();
      try
      {
         
         // Ignore any errors that might occur while closing the file handle.
         _userData->Close();
      }
      catch ( Exception^ ) 
      {
      }

   }

private:
private MyApplicationContext()
{
    _formCount = 0;

    // Handle the ApplicationExit event to know when the application is exiting.
    Application.ApplicationExit += new EventHandler(this.OnApplicationExit);

    try
    {
        // Create a file that the application will store user specific data in.
        _userData = new FileStream(Application.UserAppDataPath + "\\appdata.txt", FileMode.OpenOrCreate);
    }
    catch (IOException e)
    {
        // Inform the user that an error occurred.
        MessageBox.Show("An error occurred while attempting to show the application." +
                        "The error is:" + e.ToString());

        // Exit the current thread instead of showing the windows.
        ExitThread();
    }

    // Create both application forms and handle the Closed event
    // to know when both forms are closed.
    _form1 = new AppForm1();
    _form1.Closed += new EventHandler(OnFormClosed);
    _form1.Closing += new CancelEventHandler(OnFormClosing);
    _formCount++;

    _form2 = new AppForm2();
    _form2.Closed += new EventHandler(OnFormClosed);
    _form2.Closing += new CancelEventHandler(OnFormClosing);
    _formCount++;

    // Get the form positions based upon the user specific data.
    if (ReadFormDataFromFile())
    {
        // If the data was read from the file, set the form
        // positions manually.
        _form1.StartPosition = FormStartPosition.Manual;
        _form2.StartPosition = FormStartPosition.Manual;

        _form1.Bounds = _form1Position;
        _form2.Bounds = _form2Position;
    }

    // Show both forms.
    _form1.Show();
    _form2.Show();
}

private void OnApplicationExit(object sender, EventArgs e)
{
    // When the application is exiting, write the application data to the
    // user file and close it.
    WriteFormDataToFile();

    try
    {
        // Ignore any errors that might occur while closing the file handle.
        _userData.Close();
    }
    catch { }
}
Public Sub New()
    MyBase.New()
    _formCount = 0

    ' Handle the ApplicationExit event to know when the application is exiting.
    AddHandler Application.ApplicationExit, AddressOf OnApplicationExit

    Try
        ' Create a file that the application will store user specific data in.
        _userData = New FileStream(Application.UserAppDataPath + "\appdata.txt", FileMode.OpenOrCreate)

    Catch e As IOException
        ' Inform the user that an error occurred.
        MessageBox.Show("An error occurred while attempting to show the application." +
                        "The error is:" + e.ToString())

        ' Exit the current thread instead of showing the windows.
        ExitThread()
    End Try

    ' Create both application forms and handle the Closed event
    ' to know when both forms are closed.
    _form1 = New AppForm1()
    AddHandler _form1.Closed, AddressOf OnFormClosed
    AddHandler _form1.Closing, AddressOf OnFormClosing
    _formCount = _formCount + 1

    _form2 = New AppForm2()
    AddHandler _form2.Closed, AddressOf OnFormClosed
    AddHandler _form2.Closing, AddressOf OnFormClosing
    _formCount = _formCount + 1

    ' Get the form positions based upon the user specific data.
    If (ReadFormDataFromFile()) Then
        ' If the data was read from the file, set the form
        ' positions manually.
        _form1.StartPosition = FormStartPosition.Manual
        _form2.StartPosition = FormStartPosition.Manual

        _form1.Bounds = _form1Position
        _form2.Bounds = _form2Position
    End If

    ' Show both forms.
    _form1.Show()
    _form2.Show()
End Sub

Private Sub OnApplicationExit(ByVal sender As Object, ByVal e As EventArgs)
    ' When the application is exiting, write the application data to the
    ' user file and close it.
    WriteFormDataToFile()

    Try
        ' Ignore any errors that might occur while closing the file handle.
        _userData.Close()
    Catch
    End Try
End Sub

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.

Applies to

See also