StrataFrame Forum

Cannot close a form in the load event

http://forum.strataframe.net/Topic28889.aspx

By Ger Cannoll - 11/2/2010

This error I am getting I dont think is a SF specific error but rather a dot net error. I have some validation I do the minute I load a form. If validation fails, I then want to close the form and exit. The code I have on the Load event

if (validation = false)
{this.close();}

but I get a message :  Value Close() cannot be called while doing CreateHandle().

Do I have this code in the right place ?
By Greg McGuffey - 11/2/2010

Found this on Google:

Winforms: Close your form during Load Event
By Ger Cannoll - 11/2/2010

Hi Greg. Thaks for that and it woked fine. I had done a google search but could not find an answer as succinct as the one you located.

Not sure though how it works ?. It uses a command :

this
.BeginInvoke(new MethodInvoker(this.Close));

Why is something like this required.....must be something to do with the fact that the form is not actually loaded yet, even though its being run on the 'Load' event

By Greg McGuffey - 11/3/2010

I'm still trying to understand it myself  Blink

Here's what I've kind of figured out so far:

- apparently forms load on a different thread (or something like that), so you can't just call a method like close during the load.
- The BeginInvoke method is used to insert the close method into the message pump being used to open the form.
- This has to do with window handles and how windows manages messages. I think what is going on is that besides the stuff we normally think about, like disposing of components and controls, the close method of a form also is releasing the windows handle....which may not actually be set in the load method.  That doesn't really make sense yet as the first thing the form does is create a handle, but maybe it hasn't actually registered the handle yet with windows.  Windows handles are used to manage messages (which get translated into events for us).  In any case BeginInvoke will actually search up the windows hierarchy until it finds a valid windows handle to work with, so it apparently avoids this issue.

If that sounds kind of vague and confusing, well, it is.  Like I said I don't really understand how this works yet....