2012-06-05 55 views
6

我的應用程序是WinForms .NET 4(C#),其中一個窗體在按下按鈕後會自動關閉。奇怪:WinForms窗體在按下按鈕後自動關閉

  • 表單確實有默認的「接受」和「取消」按鈕,但這些按鈕沒有被觸摸。
  • 有一個ButtonTestConnection_Click事件,當它被點擊時,做它的工作,但以某種方式關閉表單。
  • 我使用鼠標單擊按鈕,因此這不是級聯擊鍵的情況。
  • 我不在這個函數中設置DialogResult。

我也試着檢查這個流浪。關閉/ this.Dispose調用,但沒有發現。

下面是代碼:

private void ButtonTestConnection_Click (object sender, System.EventArgs e) 
{ 
    this.Enabled = false; 
    this.Cursor = System.Windows.Forms.Cursors.WaitCursor; 

    this.ProgressBar.Minimum = 0; 
    this.ProgressBar.Maximum = 500; 
    this.ProgressBar.Value = 0; 

    this.ProgressBar.Visible = true; 
    this.ButtonTestConnection.Visible = false; 

    try 
    { 
     while (this.ProgressBar.Value < this.ProgressBar.Maximum) 
     { 
      // Some proxy code. 
      this.ProgressBar.Value++; 
     } 
    } 
    catch 
    { 
    } 

    this.ProgressBar.Visible = false; 
    this.ButtonTestConnection.Visible = true; 

    this.ProgressBar.Invalidate(); 
    System.Windows.Forms.Application.DoEvents(); 
    System.Threading.Thread.Sleep(10); 

    this.Cursor = System.Windows.Forms.Cursors.Default; 
    this.Enabled = true; 

    System.Windows.Forms.MessageBox.Show(result.ToString()); 
} 
+0

我有一種感覺,它可能是與設置按鈕不啓用這可能會改變焦點。尚未確定。 –

+1

從事件處理程序中取出所有內容,然後開始一次添加一行以找出哪一行導致問題(使用二分搜索進行優化) –

+1

重寫窗體的OnFormClosing方法。在它上面設置一個斷點,並在它命中時查看調用堆棧。如果你無法理解它,請將它發佈在你的問題中。 –

回答

14

檢查按鈕上的財產DialogResult等於None
如果不是,那麼當您按下該按鈕時,表單將被關閉,表單將返回Button的DialogResult屬性的設置。

通常情況下,這種情況發生了很多,當你複製/粘貼現有​​形式的按鈕,但忘了在粘貼鍵刪除原來的DialogResult設置

+0

爲了證明這一點,我會從事件中分離按鈕並點擊它。我敢打賭,相同的結果將會發生。 –

+0

謝謝。畢竟這是一個複製粘貼問題。我從來沒有注意到可以通過設計人員訪問DialogResult,因爲人們通常通過代碼來設置DialogResult。 –

+0

4年後...謝謝! – elmer007