Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override standard close (X) button in a Windows Form

Tags:

c#

winforms

How do I go about changing what happens when a user clicks the close (red X) button in a Windows Forms application (in C#)?

like image 575
Alex S Avatar asked Nov 03 '09 18:11

Alex S


People also ask

How do I disable the close button in Winforms?

In the Form's contructor, just set: this. ControlBox = false; You may also want to override OnClosing (http://msdn.microsoft.com/en-us/library/system.windows.forms.form.onclosing.aspx) to cancel any time the form is closed in some other fashion.

How do you close a hidden form?

In order to totally close a C# application, including the hidden forms, you can use the following command in the event code of the “Exit” control: Application. Exit(); Application.


1 Answers

You can override OnFormClosing to do this. Just be careful you don't do anything too unexpected, as clicking the 'X' to close is a well understood behavior.

protected override void OnFormClosing(FormClosingEventArgs e) {     base.OnFormClosing(e);      if (e.CloseReason == CloseReason.WindowsShutDown) return;      // Confirm user wants to close     switch (MessageBox.Show(this, "Are you sure you want to close?", "Closing", MessageBoxButtons.YesNo))     {     case DialogResult.No:         e.Cancel = true;         break;     default:         break;     }         } 
like image 115
Jon B Avatar answered Oct 01 '22 12:10

Jon B