How to clone control event handlers at runtime?

I want to duplicate a control like Button, TextBox, etc. But I donโ€™t know how I can copy event handler methods (e.g. Click ) to a new control.

I have the following code:

 var btn2 = new Button(); btn2.Text = btn1.Text; btn2.size = btn1.size; // ... btn2.Click ??? btn1.Click 

Is there any other way to duplicate a control?

+7
source share
4 answers

To clone all events of any WinForms control:

 var eventsField = typeof(Component).GetField("events", BindingFlags.NonPublic | BindingFlags.Instance); var eventHandlerList = eventsField.GetValue(button1); eventsField.SetValue(button2, eventHandlerList); 
+12
source

You just need to add an event handler for the new button control. For this, C # uses the += operator. Therefore, you can simply write:

 btn2.Click += btn1_Click 

Alternatively, a more powerful approach is to use reflection . Of particular use here is the EventInfo.AddEventHandler method.

+5
source

I didnโ€™t understand you correctly. You can attach one event to several controls like this.

 Button1.Click += button_click; Button2.Click += button_click; 
0
source

the best approach is to use a component class and inherit a control from that class

 public class DuplicateButton : OrginalButton { } 

you can make changes to the partial class, so there is no need to create events

-5
source

All Articles