I'm use this code for question before closing the application, but it is not working correctly.
My code is as below.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dlgresult = MessageBox.Show("Exit or no?",
"My First Application",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (dlgresult == DialogResult.No)
{
e.Cancel = true;
}
else
{
Application.Exit();
}
}
The return value is a value of the MessageBoxResult enumeration, where each value equates to one of the buttons that a message box can display. The default value for message box is OK because OK is the default message box button.
MessageBox is a class in C# and Show is a method that displays a message in a small window in the center of the Form. MessageBox is used to provide confirmations of a task being done or to provide warnings before a task is done.
To cancel the closure of a form, set the Cancel property of the CancelEventArgs passed to your event handler to true .
Close() will call Form. Close method of current form. When a form is closed, all resources created within the object are closed and the form is disposed.
You don't need to explicitly call Application.Exit()
since you are in the FormClosing
event which means the Closing request has been triggered(e.g. click on the cross at the form button, this.Close()
). You just need to intercept the closing request and indicate e.Cancel = true;
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(MessageBox.Show("Exit or no?",
"My First Application",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information) == DialogResult.No) {
e.Cancel = true;
}
}
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