Override standard close (X) button in a Windows Form

后端 未结 10 1598
独厮守ぢ
独厮守ぢ 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:56

    as Jon B said, but you'll also want to check for the ApplicationExitCall and TaskManagerClosing CloseReason:

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        if (  e.CloseReason == CloseReason.WindowsShutDown 
            ||e.CloseReason == CloseReason.ApplicationExitCall
            ||e.CloseReason == CloseReason.TaskManagerClosing) { 
           return; 
        }
        e.Cancel = true;
        //assuming you want the close-button to only hide the form, 
        //and are overriding the form's OnFormClosing method:
        this.Hide();
    }
    

提交回复
热议问题