0

I am using below code to exit my entire application application with YesNo question messagebox my problem is that some times I got the message twice and other times I get it correctly as one message display ..

any one can help me why that happening ??

    private void AppClose_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void F0100_FormClosing(object sender, FormClosingEventArgs e)
    {
        DialogResult result;
        result = MessageBox.Show("Are you sure you want to exit?", "Exit Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (result == DialogResult.Yes)
        {
            //Environment.Exit(1);
            Application.Exit();
        }
        else
        { e.Cancel = true; }
    }
sam
  • 2,493
  • 6
  • 38
  • 73

2 Answers2

1

I am assuming that the form in question is your main form i.e. You launch this Form as Application.Run(new Form1());

If that is the case, typically you don't need to do Application.Exit() under the Yes branch from FormClosing. So your code should be something like below

private void F0100_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason  != CloseReason.UserClosing)
        return;

    DialogResult result;
    result = MessageBox.Show("Are you sure you want to exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    if (result != DialogResult.Yes)
    {
        e.Cancel = true;
    }
}

The superfluous Application.Exit() call, creates an extra FormClosing event

NOTE: You should also check the FormClosingEventArgs.CloseReason so you don't create an extra popup when say user is logging off or killing the process.

Vikhram
  • 4,294
  • 1
  • 20
  • 32
0

Then this answer might help you some. Basically, you need to use the one you commented out: Environment.Exit(0). The Application one is a graceful attempt at exiting that attempts to close forms. Your form is still open, so it receives a 2nd FormClosing call. It's all up to timing, really, but I'd think that most of the time you'd see the prompt twice.

DonBoitnott
  • 10,787
  • 6
  • 49
  • 68