[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Learn why a form is closing in C#

form is closing

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.

Name Meaning
None Unknown reason.
WindowsShutDown Windows is shutting down.
MdiFormClosing The parent of this MDI form is closing.
UserClosing 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.
TaskManagerClosing The Task Manager is killing the form.
FormOwnerClosing The owner form is closing (for dialogs).
ApplicationExitCall 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, FormClosingEventArgs e) { MessageBox.Show(e.CloseReason.ToString()); }

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) { this.Close(); } // Invoke the application's Exit method. private void btnExit_Click(object sender, EventArgs e) { Application.Exit(); }

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; dlg.ShowDialog(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) { MyParent.Close(); }

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.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.