Partager via


Forcing handle creation in a .NET Windows Forms control

I believe no serious .NET developer has never faced a System.InvalidOperationException with an error message stating "Invoke or BeginInvoke cannot be called on a control until the window handle has been created." when trying, for example, to add text to a RichTextBox control. This type of error is caused by the fact that the underlying Windows control handle has not yet been created. You can test handle creation by calling the IsHandleCreated method on the control. To force creation of the control's handle you can simply try reading the Handle property like this:

   if (!mycontrol.IsHandleCreated)
{
// This call forces creation of the control's handle.
IntPtr handle = mycontrol.Handle;
}

This code works because the Handle property in the System.Windows.Forms.Control class makes a call to the protected method CreateHandle if the control's handle has not yet been created:

public IntPtr get_Handle()
{
if ((checkForIllegalCrossThreadCalls && !inCrossThreadSafeCall) && this.InvokeRequired)
{
throw new InvalidOperationException(SR.GetString("IllegalCrossThreadCall", new object[] { this.Name }));
}
if (!this.IsHandleCreated)
{
this.CreateHandle();
}
return this.HandleInternal;
}

Comments

  • Anonymous
    October 22, 2013
    thanks a lot  ---   works like a charm!

  • Anonymous
    January 02, 2017
    Thank you, that was very helpful