Is it possible to close a form while the constructor is executing (or simply to stop it showing at this stage)?
I have the following code:
public par
Can you make MyFunc static? and then do something like:
static void Main()
{
...
if (MyForm.MyFunc())
{
Application.Run(new MyForm());
}
}
this would essentially give you the same control over whether the form is going to be constructed or not?
I found adding a handler to the 'Load' event is better as this way the dialog is never displayed at all. With the 'Shown' event you might briefly see the dialog open and then close which may be confusing:
public partial class MyForm : Form
{
public MyForm()
{
if (MyFunc())
{
this.Load += MyForm_CloseOnStart;
}
}
private void MyForm_CloseOnStart(object sender, EventArgs e)
{
this.Close();
}
}
When you call Close() on a form, internally it is disposing of the form and releasing any managed resources. When you do this:
Application.Run(new MyForm());
You'll likely get an ObjectDisposedException. What you need to do is set the Form's visibility through a property:
Application.Run(new MyForm() { Visible = false });
Just make sure you remove the call to Close() in the constructor, or even move the property assignment there too.