How can I catch the exit event of the Winforms application?

If the user wants to exit the application by clicking on the exit icon or ALT + F4, I would like to make a dialog box asking the user if he is really sure of the exit.

How can I capture this event before the application is really closed?

+5
source share
6 answers

View the OnClosing event for the form.

Here is an excerpt from this link actually checks for a change in the text box and suggests saving:

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
   // Determine if text has changed in the textbox by comparing to original text.
   if (textBox1.Text != strMyOriginalText)
   {
      // Display a MsgBox asking the user to save changes or abort.
      if(MessageBox.Show("Do you want to save changes to your text?", "My Application",
         MessageBoxButtons.YesNo) ==  DialogResult.Yes)
      {
         // Cancel the Closing event from closing the form.
         e.Cancel = true;
         // Call method to save file...
      }
   }
}

You can change the text to suit your needs, and then, I think, you can switch DialogResult.Yesbased DialogResult.Noon your text.


Here are some modified codes for you:

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
   if(MessageBox.Show("Are you sure you want to quit?", "My Application", MessageBoxButtons.YesNo) ==  DialogResult.No)
   {
      e.Cancel = true;
   }
}
+12

Form_Closing
, , FormCloseEventArgs.Cancel true.

, Form_Load

Form1.FormClosing += new FormClosingEventHandler(Form1_Closing);

....
private void Form1_FormClosing(Object sender, FormClosingEventArgs e) 
{
    DialogResult d = MessageBox.Show("Confirm closing", "AppTitle", MessageBoxButtons.YesNo );
    if(d == DialogResult.No)
        e.Cancel = true;
}

.
, , , .

+7

Form_Closing Form_Closed .

Visual Studio . , .

+3

Is this just one form? If so, you can use an event FormClosingthat allows you to cancel it (show the dialog, then set CancelEventArgs.Cancelto true if the user decided to cancel the close).

+1
source

If you're talking about windows forms, should be enough to catch MainWindow

FormClosing , and if you want to prevent closing, just set the argument of the event handler that was run before true.

Example:

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{

      if(MessageBox.Show("Do you really want to exit?", "My Application",
         MessageBoxButtons.YesNo) ==  DialogResult.No){

                // SET TO TRUE, SO CLOSING OF THE MAIN FORM, 
                // SO THE APP ITSELF IS BLOCKED
                e.Cancel = true;            
      }
   }
}
0
source

All Articles