Tuesday, July 12, 2011

Difference between Application.Exit() and standard Close (X) button

While both Application.Exit() and the close button both terminate an application, it is still possible that they result in different behavior. The key difference is that the Application.Exit() method does not raise the Form.Closed or Form.Closing events, while the Form.Close() method does. Pressing the standard Close(X) button is equivalent to Form.Close().

The Form.Closed and Form.Closing events are obsolete since .NET 2.0. Instead, the Form.FormClosed and Form.FormClosing events should be used, which are raised by both Application.Exit() and the Form.Close() method.

The following code demonstrates these differences:

public partial class TestForm : Form
{
    public TestForm()
    {
        InitializeComponent();

        Closed += new EventHandler(TestForm_Closed);
        Closing += new CancelEventHandler(TestForm_Closing);

        FormClosed += new System.Windows.Forms.FormClosedEventHandler(TestForm_FormClosed);
        FormClosing += new System.Windows.Forms.FormClosingEventHandler(TestForm_FormClosing);

        exitButton.Click += new System.EventHandler(exitButton_Click);
        closeButton.Click += new System.EventHandler(closeButton_Click);
    }

    private void TestForm_Closed(object sender, EventArgs e)
    {
        MessageBox.Show("Form.Closed event raised by Form.Close() method.");
    }

    private void TestForm_Closing(object sender, CancelEventArgs e)
    {
        MessageBox.Show("Form.Closing event raised by Form.Close() method.");
    }

    private void TestForm_FormClosed(object sender, FormClosedEventArgs e)
    {
        MessageBox.Show("Form.FormClosed event raised by Form.Close() or Application.Exit() methods.");
    }

    private void TestForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        MessageBox.Show("Form.FormClosing event raised by Form.Close() or Application.Exit() methods.");
    }

    private void exitButton_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void closeButton_Click(object sender, EventArgs e)
    {
        Close();
    }
}