How to prevent the form from closing and display a confirmation dialog?

I want that when the user closes the window, a MessageBox appears and asks if the user is sure that he wants to close the window. But when I try, the window just closes, and nevers shows me a MessageBox.

private void SchetsWin_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing)
    {
        e.Cancel = true;
        MessageBox.Show("Example");
    }
}
+4
source share
2 answers

Instead of posting events for the form itself, simply override the OnFormClosing method. To display a confirmation message for confirmation, simply check the DialogResult value from the MessageBox:

protected override void OnFormClosing(FormClosingEventArgs e) {
  if (e.CloseReason == CloseReason.UserClosing) {        
    if (MessageBox.Show("Do you want to close?", 
                        "Confirm", 
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question) == DialogResult.No) {
      e.Cancel = true;
    }
  }
  base.OnFormClosing(e);
}

Be careful with such features, although this tends to annoy the end user.

+7
source

protected override void OnFormClosing (FormClosingEventArgs e)

        {
       if (MessageBox.Show("Are you sure you want to Close?","Confirm",MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.No)
            {
                e.Cancel = true;
            }
        }
0

All Articles