2013-03-15 23 views
1

大家。 我遇到過這樣的問題。在我的應用程序中,我通過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.. 
      } 
    } 
} 
+0

「當我點擊按鈕」時,請詳細說明您正在談論哪個按鈕? – 2013-03-15 13:51:24

回答

2

表單關閉事件每次關閉表單時都會觸發,無論這是由代碼完成還是由用戶單擊完成。

你需要的是類似的東西。

private boolean bFormCloseFlag = false; 

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 
      bFormCloseFlag = true; 
      this.Close(); 
     } 

    } 
    catch (Exception ex) 
    { 
      MessageBox.Show(ex.Message.ToString()); 
    }; 
} 


private void SecConnForm_FormClosing_1(object sender, FormClosingEventArgs e) 
{ 
    if (bFormCloseFlag = false) 
    { 
     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.. 
      } 
     } 
    } 
} 

此標誌將檢查表單是否由'X'按鈕單擊關閉或由您的代碼關閉。

+0

它的工作原理,非常感謝。 – BIB 2013-03-18 09:38:13

+0

所有最好的! :-) – 2013-03-18 10:36:04

0

的this.Close()觸發 「UserClosing」 的封閉式 可能只是隱藏對話框,而不是this.close()?

+0

無論如何,你可以添加評論來傳達你的信息:-) – 2013-03-15 14:00:12