Sunday, August 10, 2008

Winforms: Close your form during Load event:

On occasion you may find that you need to open a form and have that form then decide if it needs to remain open.

Closing a form through click of a button is normally not an issue. Its as simple as:

Me.Visible = False
or
Me
.Close

The second method will clear and remove the form from memory. But this means that the form would already have to be visible. Doing this during Form Load will cause an ObjectDisposedException.

But you want your form to close BEFORE it even becomes visible to the user? There are 2 ways to do this.

If your form is a dialog:
VB: Me.DialogResult = DialogResult.Cancel
C#: this.DialogResult = DialogResult.Cancel;

Otherwise, place this code in the form load event:
VB: Me.BeginInvoke(New MethodInvoker(AddressOf Me.Close))
C#: this.BeginInvoke(new MethodInvoker(this.Close));

4 comments:

Anonymous said...

Great Snippet!!Thanks!!

Karunakaran said...

Excellent

Unknown said...

Hi, thanks but this code causes a little problem and thats the form flickers before its closed.
any ideas ,how to solve this?

Kiavash Shakibaee said...

Hi Shahab, I think your form is still managing to load and "Show" its self before it reaches your code. If you're truely running this unload code at Form.Load, then your form should never become visible.

First make sure that this code is inside your Form.Load event. Second, you could try placing Me.Visible = False somewhere early in your form load event(but I'm not sure if this will work).