每个人。我遇到过这样的问题。在我的应用程序中,我通过 ShowDialog 方法从我的主表单中显示第二个表单。在这种形式中,我有一些文本框可以连接到数据库和一个连接按钮。如果用户单击 X,则应用程序退出。但是如果用户单击“连接” - 我连接到数据库并关闭我的第二个表单。为了捕捉关闭事件,我使用 FormClosing 方法,应用程序询问我是否要关闭应用程序,如果是,则退出。问题是当我单击按钮时,FormClosing 事件会触发并询问我是否要退出。如何避免?我尝试使用发件人,但它不起作用。
这是我的代码:
private void Connect_Click(object sender, EventArgs e)
{
    try
    {
         orcl.connect(userID.Text, Password.Text, comboTNS.Text);
         if (orcl.ifHasRows("select dbclass from setupdbversion where dbclass='SECURITY' and rownum=1"))
         {//my stuff
             this.Close();
         }
     }
     catch (Exception ex)
     {
          MessageBox.Show(ex.Message.ToString());
     };
}
private void SecConnForm_FormClosing_1(object sender, FormClosingEventArgs e)
{   
     MessageBox.Show(sender.ToString());
     if (e.CloseReason == CloseReason.UserClosing)
     {
          MessageBox.Show(sender.ToString());
          if (string.Equals((sender as Form).Name, @"SecConnForm")) //it doesn't work as in any cases the sender is my form, not a button (when i click on button of course)
          {
               if (MessageBox.Show(this, "Really exit?", "Closing...",
                    MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
                       == DialogResult.Cancel) 
                   e.Cancel = true;
               else
                   Application.Exit();
          }
          else
          {
               //other stuff goes..
          }
     }
}