Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MessageBox on Form Closing

Tags:

c#

formclosing

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();
   }
}
like image 378
Federal09 Avatar asked Sep 14 '12 02:09

Federal09


People also ask

What does MessageBox return?

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.

What is MessageBox show in C #?

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.

How do I stop a form from closing in C#?

To cancel the closure of a form, set the Cancel property of the CancelEventArgs passed to your event handler to true .

What statement closes the current form?

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.


1 Answers

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;
    }
}
like image 51
Turbot Avatar answered Sep 24 '22 05:09

Turbot