How do I go about changing what happens when a user clicks the close (red X) button in a Windows Forms application (in C#)?
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.
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.
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With