2012-06-05 56 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