我的应用程序是 WinForms .NET 4 (C#),其中一个表单在按下按钮后一直自动关闭。
- 表单确实有默认的“接受”和“取消”按钮,但未触及这些按钮。
- 有一个 ButtonTestConnection_Click 事件,当点击该事件时,它会完成它的工作,但会以某种方式关闭表单。
- 我使用鼠标单击按钮,因此这不是级联击键的情况。
- 我没有在此函数中设置 DialogResult。
我还尝试检查是否有杂散的 this.Close/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());
}
最佳答案
检查按钮上的属性 DialogResult
是否等于 None
。
否则,当您点击该按钮时,表单将关闭,并且表单将返回按钮的 DialogResult 属性的设置。
通常,当您复制/粘贴现有表单的按钮但忘记删除粘贴按钮上的原始 DialogResult 设置时,这种情况经常发生
关于c# - 奇怪的 : WinForms form closes automatically after button press,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10900569/