Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent a form from closing and display a confirmation dialog?

Tags:

c#

.net

winforms

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

private void SchetsWin_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing)
    {
        e.Cancel = true;
        MessageBox.Show("Example");
    }
}
like image 718
Max Ruigewaard Avatar asked Jan 12 '23 00:01

Max Ruigewaard


1 Answers

Instead of wiring an event for the form itself, just override the OnFormClosing method. As far as displaying a confirmation message to confirm it, just check the value of the DialogResult of 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 functions like this though — it has a tendency to annoy the end user.

like image 174
LarsTech Avatar answered Jan 28 '23 10:01

LarsTech