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

前端 未结 12 1052
野性不改
野性不改 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:08

    I always use a Form Close method in my applications that catches alt + x from my exit Button, alt + f4 or another form closing event was initiated. All my classes have the class name defined as Private string mstrClsTitle = "grmRexcel" in this case, an Exit method that calls the Form Closing Method and a Form Closing Method. I also have a statement for the Form Closing Method - this.FormClosing = My Form Closing Form Closing method name.

    The code for this:

    namespace Rexcel_II
    {
        public partial class frmRexcel : Form
        {
            private string mstrClsTitle = "frmRexcel";
    
            public frmRexcel()
            {
                InitializeComponent();
    
                this.FormClosing += frmRexcel_FormClosing;
            }
    
            /// 
            /// Handles the Button Exit Event executed by the Exit Button Click
            /// or Alt + x
            /// 
            /// 
            /// 
            /// 
            private void btnExit_Click(object sender, EventArgs e)
            {            
                this.Close();        
            }
    
    
            /// 
            /// Handles the Form Closing event
            /// 
            /// 
            /// 
            /// 
            private void frmRexcel_FormClosing(object sender, FormClosingEventArgs e)
            {
    
                // ---- If windows is shutting down, 
                // ---- I don't want to hold up the process
                if (e.CloseReason == CloseReason.WindowsShutDown) return;
                {
    
                    // ---- Ok, Windows is not shutting down so
                    // ---- either btnExit or Alt + x or Alt + f4 has been clicked or
                    // ---- another form closing event was intiated
                    //      *)  Confirm user wants to close the application
                    switch (MessageBox.Show(this, 
                                        "Are you sure you want to close the Application?",
                                        mstrClsTitle + ".frmRexcel_FormClosing",
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                    {
    
                        // ---- *)  if No keep the application alive 
                        //----  *)  else close the application
                        case DialogResult.No:
                            e.Cancel = true;
                            break;
                        default:
                            break;
                    }
                }
            }
        }
    }
    

提交回复
热议问题