Closing a form during a constructor
The only thing you could do it set a flag to close it in the constructor, and then closing it in the Shown
event. Of course, if you're doing that, it makes sense to move the code to determine whether it should be closed there in the first place.
The following works well:
public partial class MyForm : Form
{
public MyForm()
{
if (MyFunc())
{
this.Shown += new EventHandler(MyForm_CloseOnStart);
}
}
private void MyForm_CloseOnStart(object sender, EventArgs e)
{
this.Close();
}
}
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;
}
// ...
}
// ...
}