Override standard close (X) button in a Windows Form

后端 未结 10 1599
独厮守ぢ
独厮守ぢ 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 09:00

    This is a pretty commonly asked question. One good answer is here:

    VB.NET overload default functionality when user clicks the X (Close Program)


    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)

提交回复
热议问题