miky
miky

Reputation: 449

On CloseReason.UserClosing form is showing dialog for close 2 times

I want to show dialog when user is trying to close app(red windows cross and button on my form) but when windows is shutting down, this dialog blocking the shutdown, so I wan to want detect by app when is windows shutting down and proceed without dialog. Here is my code

after form load Im catching close event:

this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);

and

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        switch (e.CloseReason)
        {
            case CloseReason.UserClosing:
                if (MessageBox.Show("Do you want to exit the application?", "Your App", MessageBoxButtons.YesNo) == DialogResult.No)
                    {
                        e.Cancel = true;
                    }
                break;
            case CloseReason.WindowsShutDown:
                e.Cancel = false; //this is propably dumb
                break;
            default:
                break;
        }
    }

But when user is closing app, dialog is shown 2 times. First dialog dotn do anything, action is taken after second dialog. How can I show dialog for closing only once and no dialog when windows is shutting down(because windows is waiting for my app to close)?

Upvotes: 2

Views: 1992

Answers (1)

LarsTech
LarsTech

Reputation: 81675

The better way to write this code (my opinion) is to not subscribe to the form events, but to use the available override method:

protected override void OnFormClosing(FormClosingEventArgs e)
{
  switch (e.CloseReason)
  {
    case CloseReason.UserClosing:
      if (MessageBox.Show("Do you want to exit the application?", "Your App", MessageBoxButtons.YesNo) == DialogResult.No)
      {
        e.Cancel = true;
      }
      break;
    case CloseReason.WindowsShutDown:
      e.Cancel = false; //this is propably dumb
      break;
    default:
      break;
    }

  base.OnFormClosing(e);
}

You might want to consider using just an if (e.CloseReason == CloseReason.UserClosing) instead of the switch statement based on its current form. e.Cancel is already False by default so you do not need to exclicitly set it.

Upvotes: 4

Related Questions