在构造函数期间关闭表单 [英] Closing a form during a constructor
问题描述
是否可以在构造函数执行时关闭表单(或只是在此阶段停止显示)?
Is it possible to close a form while the constructor is executing (or simply to stop it showing at this stage)?
我有以下代码:
public partial class MyForm : Form
{
public MyForm()
{
if (MyFunc())
{
this.Close();
}
}
}
在 Main() 中抛出 ObjectDisposedException,这里:
Which throws an ObjectDisposedException in Main(), here:
static void Main()
{
...
// Following line errors
Application.Run(new MyForm());
}
我试过像这样检查 MyForm 的结果:
I’ve tried checking the result of MyForm like this:
static void Main()
{
...
MyForm frm = new MyForm();
if (frm != null)
{
// Following line errors
Application.Run(frm);
}
}
但这似乎没有帮助.任何人都可以告诉我解决这个问题的方法吗?也许是一种检查表单以查看它是否仍然存在的方法?
But that doesn’t seem to help. Can anyone tell me a way around this, please? Maybe a way to check the form to see if it still exists?
推荐答案
从 Form 的构造函数调用 Close
是不可能的,因为它会调用 Dispose
尚未创建的表单.要在构建后关闭表单,请将匿名事件处理程序分配给 Load
事件 在它第一次显示之前关闭你的表单:
Calling Close
from the constructor of the Form is not possible, as it will call Dispose
on a Form that has not yet been created. To close the Form after construction, assign an anonymous event handler to the Load
event that closes your Form before it is displayed for the first time:
public partial class MyForm : Form
{
public MyForm()
{
if (ShouldClose())
{
Load += (s, e) => Close();
return;
}
// ...
}
// ...
}
这篇关于在构造函数期间关闭表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!