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?
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.
To cancel the closure of a form, set the Cancel property of the CancelEventArgs passed to your event handler to true .
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;
}
// ...
}
// ...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With