Question

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.

Était-ce utile?

La solution

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;
        }
    }

Autres conseils

Use the form's FormClosing event of your program window. You can then set e.Cancel to true if the user clicks no:

this.FormClosing += (s, e) => {
  DialogResult dialog = dialog = MessageBox.Show("Really close?", "SomeTitle",
    MessageBoxButtons.YesNo);
  if (dialog == DialogResult.No)
  {
    e.Cancel = true;
  }
};

I guess you are using FormClosed. Are you? Then it's too late.

Try this

        this.FormClosing += new FormClosingEventHandler(delegate(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("Do you really want to exit this application?", MessageBoxButtons:=MessageBoxButtons.YesNo) == DialogResult.No)
            {
                e.Cancel = true;
            }
        });

Refer to Mudu's answer.

Basically unless you specify additional parameters to MessageBox.Show() you cannot get any result other than DialogResult.Ok from a default MessageBox.

The code you posted (minus your little typo of dialog = dialog =) works exactly as expected to me.

Also: Application.Exit() IS the correct way of closing an application :)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top