Application Close on DialogResult

Nicky picture Nicky · May 8, 2012 · Viewed 9.8k times · Source

I have a C# GUI application. When the user clicks on the red 'X' (for closing the app) I want to show a message and ask if he really wants to close it.

I found a solution:

        DialogResult dialog = MessageBox.Show("Do you really want to close the program?", "SomeTitle", MessageBoxButtons.YesNo);
        if (dialog == DialogResult.Yes)
        {
            Application.Exit();
        }else if (dialog == DialogResult.No)
        {
          //don't do anything
        }

When the user clicks 'yes', the application should terminate completely. (Is Application.Exit() correct for this purpose?)

When the user clicks 'no', the DialogResult/MessageBox should close, but the application should stay opened. However, it closes!!

How can I avoid this?

BTW: I use Visual Studio 2010 and Winforms.

Answer

Gustavo F picture Gustavo F · May 8, 2012

Use the FormClosing event from the Form, and the FormClosingEventArgs to cancel the process.

example:

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        DialogResult dialog = dialog = MessageBox.Show("Do you really want to close the program?", "SomeTitle", MessageBoxButtons.YesNo);
        if (dialog == DialogResult.No)
        {
            e.Cancel = true;
        }
    }