Search code examples
c#winformsformclosing

Creating program in C#, FormClosing event executes twice


As I said in the title I am creating a program. However, I am facing the problem of the FormClosing event executing twice. The message box appears and the buttons perform their purpose well, but when I click "Yes" or "No", it repeats itself. Thankfully the "Cancel" button doesn't have this problem.

private void Form1_FormClosing (object sender, FormClosingEventArgs e)
{
    DialogResult dialog = MessageBox.Show("Do you want to save your progress?", "Media Cataloguer", MessageBoxButtons.YesNoCancel);

    if (dialog == DialogResult.Yes)
    {
        SaveFileDialog savefile = new SaveFileDialog();
        savefile.Filter = "Text files|*.txt";
        savefile.Title = "Save As";
        savefile.ShowDialog();
        System.IO.FileStream fs = (System.IO.FileStream)savefile.OpenFile();
        Application.Exit();
    }
    else if (dialog == DialogResult.No)
    {
        MessageBox.Show("Are you sure?", "Media Cataloguer", MessageBoxButtons.YesNo);
        Application.Exit();
    }
    else if (dialog == DialogResult.Cancel)
    {
        e.Cancel = true;
    }
}

Nothing else I have found had helped me very much. Like I said earlier, the message box appears twice. That is my only problem. Everything else for this void works fine.


Solution

  • Your problem is that you are calling Application.Exit(). As MSDN says,

    The Exit method stops all running message loops on all threads and closes all windows of the application

    In other words, it will fire the form closing event again.

    To get around this, use Environment.Exit(0) instead.