Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

I have the following code:

public partial class MyForm : Form
{        
    public MyForm()
    {
        if (MyFunc())
        {
            this.Close();
        }
    }
}

Which throws an ObjectDisposedException 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?

like image 762
Paul Michaels Avatar asked Oct 06 '22 07:10

Paul Michaels


People also ask

How do I close a ShowDialog form?

To close a form, you just need to set the form's DialogResult property (to any value by DialogResult. None ) in some event handler. When your code exits from the event handler the WinForm engine will hide the form and the code that follows the initial ShowDialog method call will continue execution.

How do I cancel a form closing?

To cancel the closure of a form, set the Cancel property of the CancelEventArgs passed to your event handler to true .


2 Answers

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;
        }

        // ...
    }

    // ...
}
like image 112
Christian Avatar answered Oct 23 '22 12:10

Christian


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.

like image 22
ErikHeemskerk Avatar answered Oct 23 '22 12:10

ErikHeemskerk