BeginInvoke claims the control's window handle has not been created even though I think it was

StackOverflow https://stackoverflow.com/questions/13090097

  •  14-07-2021
  •  | 
  •  

Question

In my form's constructor, I call:

InitializeComponent(); // boilerplate placed by VS, initializing controls
label1.BeginInvoke(new InvokeDelegate(RefreshLabelDelegate));

Yet, I get the dreaded exception with the message:

"Invoke or BeginInvoke cannot be called on a control until the window handle has been created"

AFAIK, it is all the same thread, so why the exception?

Was it helpful?

Solution

Move label1.BeginInvoke from constructor to Form_Load event handler.

OTHER TIPS

The native window handle does not get created in the constructor. It doesn't happen until later, after the Show() method of the form is called. In typical .NET lazy fashion. The Load event is the first standard event that runs after it is created. There's also the HandleCreated event but it may run more than once.

It is very unlikely that you actually need to use BeginInvoke here, it is meant to be used to have code run on the thread that created the Label1 control. The constructor should already be running on that thread, it is very unhealthy if it is not. If painting the label was intended then use the Form's Shown event instead, the first event that runs after the form is actually visible to the user.

The handle isn't yet created (why do you say that it is). The handle isn't created at construction--it is delayed. You can workaround this by forcing the creation of the handle by accessing the control's .Handle property.

The following might be helpful:

Do not call BeginInvoke, there is no reason. In the constructor of a control you had better already be on the appropriate UI thread.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top