How do I go about changing what happens when a user clicks the close (red X) button in a Windows Forms application (in C#)?
This is a pretty commonly asked question. One good answer is here:
If you don't feel comfortable putting your code in the Form_Closing event, the only other option I am aware of is a "hack" that I've used once or twice. It should not be necessary to resort to this hack, but here it is:
Don't use the normal close button. Instead, create your form so that it has no ControlBox. You can do this by setting ControlBox = false on the form, in which case, you will still have the normal bar across the top of the form, or you can set the form's FormBorderStyle to "None. If you go this second route, there will be no bar across the top, or any other visible border, so you'll have to simulate those either by drawing on the form, or by artistic use of Panel controls.
Then you can add a standard button and make it look like a close button, and put your clean-up code in there. At the end of the button event, just call this.Close()
(C#) or Me.Close()
(VB)
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;
}
}
Either override the OnFormClosing or register for the event FormClosing.
This is an example of overriding the OnFormClosing function in the derived form:
protected override void OnFormClosing(FormClosingEventArgs e)
{
e.Cancel = true;
}
This is an example of the handler of the event to stop the form from closing which can be in any class:
private void FormClosing(object sender,FormClosingEventArgs e)
{
e.Cancel = true;
}
To get more advanced, check the CloseReason property on the FormClosingEventArgs to ensure the appropriate action is performed. You might want to only do the alternative action if the user tries to close the form.