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");
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With