Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Control.IsHandleCreated needed for?

I'm examining the source of the built-in .net control for TabControl, and I see that it references this property before deciding whether to Add or Insert a TabPage to the collection.

if (this.owner.IsHandleCreated)
{
    this.owner.AddTabPage(tabPage, tabPage.GetTCITEM());
}
else
{
    this.owner.Insert(this.owner.TabCount, tabPage);
}

Both functions ultimately accomplish the same goal - they add the TabPage to the end of the internal "TabPages" collection... but I just don't see why it should matter which function you use.

this refers to the ControlCollection that overrides the built-in Control.ControlCollection. owner is the TabControl that is making use of the ControlCollection.

like image 783
Mirrana Avatar asked Feb 06 '12 03:02

Mirrana


1 Answers

TabControl's AddTabPage method (the one that is called when the handle is created) calls the AddNativeTabPage method. That in turn calls SendMessage and PostMessage (effectively, Control.Invoke and Control.BeginInvoke) to add the tab page. These methods marshal the addition of the tab page to the UI thread, so that the control is internally obeying the rule that you shouldn't interact with UI controls from a background thread.

This actually means that if the handle has been created, AddTabPage is safe to call from non-UI threads (very unusual for a UI control!). Unfortunately, this also means that the AddTabPage method would block if the TabControl didn't yet have a handle, because there would be no UI thread pumping messages, and so it shouldn't be called unless the handle was created.

For the curious, this is in the TabControl.ControlsCollection class, in the Add method.

like image 68
Chris Shain Avatar answered Sep 28 '22 19:09

Chris Shain