Reputation: 1179
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?
Upvotes: 3
Views: 3044
Reputation: 4014
Do not call BeginInvoke, there is no reason. In the constructor of a control you had better already be on the appropriate UI thread.
Upvotes: 0
Reputation: 17474
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:
Upvotes: 2
Reputation: 942267
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.
Upvotes: 4
Reputation: 9519
Move label1.BeginInvoke
from constructor to Form_Load
event handler.
Upvotes: 4