Reputation: 2989
My application is closing when I press Alt + F4. How I will do to have a MessageBox to show first for confirmation before exiting and if No is response the applcation will not continue to close?
Upvotes: 2
Views: 6025
Reputation: 28588
On FormClosing() event add this code:
private void MyForm_Closing(object sender, CancelEventArgs e)
{
if(MessageBox.Show("Are you sure want to exit the App?", "Test", MessageBoxButtons.YesNo) == DialogResult.No)
{
e.Cancel = true;
}
}
Upvotes: 0
Reputation: 273804
In addition to the answers already posted here, don't be the dork that hangs the complete system:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason != CloseReason.UserClosing)
{
e.Cancel = false;
return;
}
// other logic with Messagebox
...
}
Upvotes: 8
Reputation: 34218
Handle the Form.Closing
event, which takes a CancelEventArgs
as parameter. In that handler, show your messagebox. If the user wishes to cancel, set the property .Cancel
of the event args to true
, like this:
private void Form1_Closing(object sender, CancelEventArgs e)
{
var result = MessageBox.Show("Do you really want to exit?", "Are you sure?", MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
e.Cancel = true;
}
}
Upvotes: 4