Override standard close (X) button in a Windows Form

后端 未结 10 1597
独厮守ぢ
独厮守ぢ 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条回答
  •  猫巷女王i
    2020-12-04 08:53

    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.

提交回复
热议问题