Tip: Use Form.Close() opposed to Application.Exit()


When closing your application from code, for example in the File | Exit menu you should use Form.Close() (ie this.Close() or Me.Close) opposed to Application.Exit().  When calling Application.Exit everything is told to stop immediately and then the appplication is shutdown.  Resulting in events like Form.Closed and Form_Closing not being fired.  The MSDN documentation explains more precisely what happens - Application Exit Method 

GOOD
private void mnuFileExit_Click(object sender, System.EventArgs e) {
   
this.Close();   // Closes application nicely as you would expect.
}

private void FormMain_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
   
// Gets Fired, Yeah!
}

BAD
private void mnuFileExit_Click(object sender, System.EventArgs e) {
    Application.Exit();   // Brings application to a screeching halt. Leads to bugs.
}

private void FormMain_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
   
// Does not get fired, 🙁
}

Comments (5)
  1. ramanujam says:

    Tom

    What if I call Application.exit() in FormClosing event handler.Is it recommended?

    Regards

    Rama

  2. R. Bemrose says:

    This documentation is woefully out of date, particularly when it has such a high google ranking for Application.exit CancelEventArgs.

    In .NET 2.0 and higher, when you call Application.Exit(), every form's FormClosing event is called.  Any form can then cancel the Exit by setting e.cancel = true; (assuming your FormClosingEventArgs is named e, which is the default).

  3. Markus says:

    From msdn.microsoft.com/…/ms157894(v=vs.80).aspx

    about Application.Exit:

    "A FormClosing event is raised for every form represented by the OpenForms property."

  4. Fanch says:

    From msdn.microsoft.com/…/ms157894(v=vs.80).aspx

    Prior to .NET Framework version 2.0, the Exit method did not raise the equivalent events for the Form class (Closed and Closing). In order to force these events, it was necessary to explicitly call the Close method for each open form before calling the Exit method.

Comments are closed.

Skip to main content