3

I want to make a MessageBox confirmation. Here is the message box:

DialogResult dialog = MessageBox.Show("Etes vous sûre de vouloir fermer le programme ?", "Exit",MessageBoxButtons.YesNo);
if (dialog == DialogResult.Yes)
{
  Application.Exit();
}
else if (dialog == DialogResult.No)
{
    e.Cancel = true;
}

The problem is, when I click the YES Button, the popup does not close automatically. It will be closed after I click 2 times again. It should be closed from the first time.

It seems pretty easy but I'm not sure where is my mistake;

reduckted
  • 2,358
  • 3
  • 28
  • 37
Y.Arsoy
  • 129
  • 1
  • 3
  • 10
  • 5
    from that code, theres no obvious reason - however depending on where that code is, that could be the reason.. in the wrong place it can cause the event to be triggered more than once – BugFinder Apr 28 '16 at 07:36

4 Answers4

7

If it's in main form close method you can use it like this:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("Really close?", "Exit", MessageBoxButtons.YesNo) ==
        System.Windows.Forms.DialogResult.No)
        e.Cancel = true;
}

If user press "Yes" your form will be closed due to no close cancellation. If it is not main form close doesn't mean application exit. In this case you can close parent form explicitly after ShowDialog call.

Dmitriy Zapevalov
  • 1,357
  • 8
  • 13
4

Below is code to prompt message (Yes/No):

DialogResult dialogResult = MessageBox.Show("Are you sure to delete Yes/No", "Delete", MessageBoxButtons.YesNo);

if (dialogResult == DialogResult.Yes)
{
   /// do something here        
}
Anjan Kant
  • 4,090
  • 41
  • 39
1

Call Application.DoEvents() before Application.Exit(). But it is better to close parent form with Close() instead of Application.Exit.

i486
  • 6,491
  • 4
  • 24
  • 41
0
switch (MessageBox.Show("Etes vous sûre de vouloir fermer le programme ?", "Your_Application_Name", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
        {
            case DialogResult.Yes:
                Application.Exit();
                break;
            case DialogResult.No:
                //Action if No
                break;

        }