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.
Hans passant
source share