views:

139

answers:

4

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 partial class MyForm : Form
{        
    public MyForm()
    {
         if (MyFunc())
            {
                this.Close();
            }
       }
}

Which errors in Main(), here:

    static void Main()
    {            
        ...

    // Following line errors
        Application.Run(new 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?

+1  A: 

Your form won't be opened from the constructor. What are you trying to achieve?

If you close this form then the code path will exit completely, leaving you with no obvious benefit (ie, Application.Run will exit). Someone else posted code about making the form hidden, seems more probable.

Adam
+1  A: 

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?

Mauro
+3  A: 

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.

Matthew Abbott
+1  A: 

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.

ErikHeemskerk