Override standard close (X) button in a Windows Form

后端 未结 10 1609
独厮守ぢ
独厮守ぢ 2020-12-04 08:43

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

10条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 08:58

    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;
        }        
    }
    

提交回复
热议问题