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.
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; } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.