How do I go about changing what happens when a user clicks the close (red X) button in a Windows Forms application (in C#)?
See Question&Answers more detail:osHow do I go about changing what happens when a user clicks the close (red X) button in a Windows Forms application (in C#)?
See Question&Answers more detail:osYou 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;
}
}