Freigeben über


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

  • Anonymous
    December 10, 2007
    Tom What if I call Application.exit() in FormClosing event handler.Is it recommended? Regards Rama

  • Anonymous
    January 21, 2009
    PingBack from http://www.keyongtech.com/461264-program-shut-down

  • Anonymous
    November 14, 2011
    The comment has been removed

  • Anonymous
    October 29, 2012
    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."

  • Anonymous
    March 14, 2013
    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.