Reputation: 45
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");
}
}
Upvotes: 4
Views: 2738
Reputation: 26209
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; } }
Upvotes: 0
Reputation: 81675
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.
Upvotes: 9