I thought my code was safe, but it is not.
I am using a form to display some messages that are created and managed somewhere else in my app.
To get to this message I am using a delegate that I add to my external event in the form.load event.
private void ErrorLog_Load( object sender, EventArgs e )
{
//error handler has been properly initialized in the ctor
Handler.getInstance( ).errorOccured += errorHandler;
}
I the callback of the form I need to invoke:
protected void handleError( SenderInfo sender, ErrorEventArgument argument )
{
if (this.InvokeRequired)
{
this.Invoke(errorHandler, new object[] { sender, argument });
}
else
{
//update the form
}
}
And in the closed/ closing event the callback is unregistered.
Now I have a situation where the window is created as an mdi child an obviously not shown (hidden by another mdi window) and the app crashes in handleError at the line with Invoke with the message that the window handle has not been created.
So three questions:
At which point in time is the window handle of the form created
Appart from adding this.IsHandleCreated to my handleError how should I improve my code
What is the correct event to unregister the callback?
TIA
Mario
I think the handle is meant to be created when the
HandleCreatedevent is called (available in .NET 3.5 but it is hidden in the designer), but I don’t think that’s exactly true as you also need to getthis.Handle. I saw a better event in the .NET 4 docs but I don’t know for sure about that. The most stable way I’ve come up with in v3.5 is something like this in the constructor, but the window seems to flash up so not sure if this will work without the window ever becoming visible:I suppose you would unregister your callback in the
FormClosingevent.