How to know user has clicked “X” or the “Close” button?

前端 未结 12 991
野性不改
野性不改 2020-11-27 12:19

In MSDN I found CloseReason.UserClosing to know that the user had decided to close the form but I guess it is the same for both clicking the X button or clickin

12条回答
  •  有刺的猬
    2020-11-27 13:03

    I also had to register the closing function inside the form's "InitializeComponent()" method:

    private void InitializeComponent() {
    // ...
    this.FormClosing += FrmMain_FormClosing;
    // ...
    }
    

    My "FormClosing" function looks similar to the given answer (https://stackoverflow.com/a/2683846/3323790):

    private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) {
        if (e.CloseReason == CloseReason.UserClosing){
            MessageBox.Show("Closed by User", "UserClosing");
        }
    
        if (e.CloseReason == CloseReason.WindowsShutDown){
            MessageBox.Show("Closed by Windows shutdown", "WindowsShutDown");
        }
    }
    

    One more thing to mention: There is also a "FormClosed" function which occurs after "FormClosing". To use this function, register it as shown below:

    this.FormClosed += MainPage_FormClosed;
    
    private void MainPage_FormClosing(object sender, FormClosingEventArgs e)
    {
    // your code after the form is closed
    }
    

提交回复
热议问题