How often is the UserControl handle restored?

I looked at the UserControl.Load event for winforms (found here ) in msdn and saw this warning message:

The load event occurs when creating a handle for UserControl. In some cases, this may trigger a load event more than once. For example, the Load event occurs when the UserControl and again if the handle is recreated. (One of the ways the handle is recreated by calling the RecreateHandle method.) To note that the Load event occurs more than once, you must place any initialization code once in the UserControl constructor instead of the load event handler. In addition, you should not add binding data to UserControl in the load event handler.

The question then becomes, what, in addition to explicitly calling RecreateHandle, will lead to the creation of a handle for UserControl? Before reading this, I always set everything that should happen only once in the Load event. Also (from the last sentence), where is the best place to add data bindings? Does it really matter if I don't call RecreateHandle?

+8
events winforms user-controls
source share
1 answer

Yes it is possible. This is caused by a problem with the native Windows API function CreateWindowEx (). This call indicates the style bits for the window. The same style bits are also displayed as properties of the control. The problem is that you need to call CreateWindowEx () again to change this property. The native Windows window for the control is destroyed and recreated. It has side effects, one of them returns a load event again.

Demonstrating it using code:

public partial class UserControl1 : UserControl { public UserControl1() { InitializeComponent(); } public void TriggerRecreate() { if (this.RightToLeft == System.Windows.Forms.RightToLeft.Yes) this.RightToLeft = System.Windows.Forms.RightToLeft.No; else this.RightToLeft = System.Windows.Forms.RightToLeft.Yes; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); Console.WriteLine("onload"); } } 

Compile and omit the control on the form. Add button:

  private void button1_Click(object sender, EventArgs e) { userControl11.TriggerRecreate(); } 

And note that the Output window displays "onload" every time you click a button.

The RightToLeft property is the only thing I can come up with for UserControl to do this. There are many more for Form. However, this class is intended to prevent the use of the OnLoad method more than once. Not sure why they did not do this for UserControl, probably because it is so rare. Feel free to ignore it. And always support the constructor over the Load event if you don't care about the size of the window.

+7
source share

All Articles