Reputation: 5858
I have a main form called Form_Main
, when somebody wants to close it, it will close the entire application (by entire application I mean quitting other forms as well). Therefore I prepared a yes/no MessageBox that ask users if they really want to quit the form. Here's where I'm at:
private void Form_Main_FormClosed(object sender, FormClosedEventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure?", "Confirmation", MessageBoxButtons.OKCancel);
if (result == DialogResult.OK)
{
Environment.Exit(1);
}
else
{
//does nothing
}
}
The "OK" button works. But when users clicks "Cancel", Form_Main
is closed, but the application is still running (other forms are untouched). What should I replace //does nothing
with?
Upvotes: 2
Views: 45
Reputation: 66489
Use the FormClosing
event (instead of FormClosed
), and then set e.Cancel = true
:
private void Form_Main_FormClosing(object sender, FormClosingEventArgs e)
{
var result = MessageBox.Show("Are you sure?", "Confirmation", MessageBoxButtons.OKCancel);
e.Cancel = (result != DialogResult.OK);
}
The FormClosing
event occurs before the form actually closes, so you still have a chance to cancel it. By the time you get to the FormClosed
event, it's too late.
Upvotes: 6