Override standard close (X) button in a Windows Form

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

    The accepted answer works quite well. An alternative method that I have used is to create a FormClosing method for the main Form. This is very similar to the override. My example is for an application that minimizes to the system tray when clicking the close button on the Form.

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.ApplicationExitCall)
            {
                return;
            }
            else
            {
                e.Cancel = true;
                WindowState = FormWindowState.Minimized;
            }            
        }
    

    This will allow ALT+F4 or anything in the Application calling Application.Exit(); to act as normal while clicking the (X) will minimize the Application.

提交回复
热议问题