0

I made an exit button as menu item with confirmation message and below code do the job,.. but when I am trying to handle the X button I am getting the confirmation message twice I tried to comment the message on the exit button on the menu item but still getting the message twice when I click on YES

    private void ExitMenuItem_Click(object sender, EventArgs e)
    {
        /*DialogResult result;

        result = MessageBox.Show("are you sure?", "exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (result == DialogResult.Yes)
        {
            Application.Exit();
        }
        else 
        { return; }*/
    }

    private void F0101_FormClosing(object sender, FormClosingEventArgs e)
    {
        DialogResult result;

        result = MessageBox.Show(""are you sure?", "exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (result == DialogResult.Yes)
        {
            Application.Exit();
        }
        else
        { e.Cancel = true; }
    }
samer
  • 193
  • 5
  • 21
  • Did you name your form `F010`? – Dai Jul 16 '16 at 13:59
  • Is this the first form of your application? The one that is started by Application.Run in your Program.cs? – Steve Jul 16 '16 at 14:00
  • Always pay attention to `e.CloseReason` in your event handler. You most certainly don't want to display this message box when it is CloseReason.WindowsShutdown. And, as you found out, you don't want to display it either when it is CloseReason.ApplicationExitCall. Only display it when it is CloseReason.UserClosing – Hans Passant Jul 16 '16 at 15:34
  • @Dai yes F0101 is the name of my form – samer Jul 17 '16 at 04:46
  • @Steve no its not the first form of my application actually it called by another form... – samer Jul 17 '16 at 04:47

1 Answers1

3

Application.Exit() sends a message to your application to close again, use:

Environment.Exit(0);

Application.Exit Docs:

Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.

Environment.Exit Docs:

Terminates this process and returns an exit code to the operating system.

So using Environment, the process is terminated. Even you call it inside a try..finally block, the finally block doesn't execute.

However, Application.Exit can be used when you need a chance to execute state saving code in the closing events (which is in your case calling the same method and thus showing the method twice).

Zein Makki
  • 29,485
  • 6
  • 52
  • 63