Title: Learn why a form is closing in C#
You can learn why a form is closing by using the form's FormClosing event handler. The event handler's e parameter has a property CloseReason that tells you why the form is closing.
The CloseReason can be one of the following values.
||Windows is shutting down.
||The parent of this MDI form is closing.
||The user is closing the form by clicking the close (X) button, using the form's system menu, or pressing Alt-F4. This is also the reason if the code calls the form's Close method.
||The Task Manager is killing the form.
||The owner form is closing (for dialogs).
||The program called Application.Exit.
This example uses the following code to display the form's closing reason to the user.
// Tell the user why the form is closing.
private void Form1_FormClosing(object sender,
The program's Close and Exit buttons are straightforward. The following code shows how those buttons close the form.
// Close the form.
private void btnClose_Click(object sender, EventArgs e)
// Invoke the application's Exit method.
private void btnExit_Click(object sender, EventArgs e)
If you click the Dialog button, the following code displays a new instance of the form as a dialog.
// Display the form as a dialog.
private Form1 MyParent;
private void btnDialog_Click(object sender, EventArgs e)
Form1 dlg = new Form1();
dlg.btnClose.Visible = false;
dlg.btnExit.Visible = false;
dlg.btnDialog.Visible = false;
dlg.btnCloseParent.Visible = true;
dlg.MyParent = this;
This code creates a new instance of the form. It hides the Close, Exit, and Dialog buttons, and displays the Close Parent button. It saves a reference to the current form (the parent of the dialog) and displays the dialog.
The following code shows how the dialog's Close Parent button closes the dialog's parent.
// Close the parent form.
private void btnCloseParent_Click(object sender, EventArgs e)
This code simply calls the parent form's Close method.
Together the buttons let you close the form in every way other than using the Task Manager. Use the Task Manager to try that one.
Download the example to experiment with it and to see additional details.