//右上角的X
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if( DialogResult.OK==MessageBox.Show("   确定退出?","退出",MessageBoxButtons.OKCancel))
{
if( DialogResult.OK==MessageBox.Show("  是否保存该项目!","保存",MessageBoxButtons.OKCancel))
{
menuItem9_Click(sender,e);
}
this.Dispose();
}
}运行程序,点击窗体右上角的X,出现“确定退出”对话框的时候,我选择cancel后,窗体还是退出了?请问这里我该如何操作?

解决方案 »

  1.   

    如果不想关闭窗口,设置e.Cancel = false。
      

  2.   

    The following example uses a CancelEventArgs and a CancelEventHandler to handle the Closing event of a Form. This code assumes that you have created a Form with a class-level Boolean variable named isDataSaved. It also assumes that you have added a statement to invoke the OtherInitialize method from the form's Load method or the constructor (after the call to InitializeComponent). 
    C#  Copy Code 
    // Call this method from the constructor of your form
        private void OtherInitialize() {
           this.Closing += new CancelEventHandler(this.Form1_Closing);
           // Exchange commented line and note the difference.
           this.isDataSaved = true;
           //this.isDataSaved = false;
        }    private void Form1_Closing(Object sender, CancelEventArgs e) {
           if (!isDataSaved) {
              e.Cancel = true;
              MessageBox.Show("You must save first.");
           }
           else {
              e.Cancel = false;
              MessageBox.Show("Goodbye.");
           }
        }
     
    看MSDN
      

  3.   

    private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
    if( DialogResult.OK==MessageBox.Show("   确定退出?","退出",MessageBoxButtons.OKCancel) == DialogResult.OK)
    {
    if( DialogResult.OK==MessageBox.Show("  是否保存该项目!","保存",MessageBoxButtons.OKCancel) == DialogResult.OK)
    {
    menuItem9_Click(sender,e);
                      this.Dispose();
    }
             else
                      {e.Cancel = true;}
    }
             else
             {
                e.Cancel = true;//不关闭
             }
    }