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.
Click
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?
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);
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.
EventInfo.AddEventHandler
I didnโt understand you correctly. You can attach one event to several controls like this.
Button1.Click += button_click; Button2.Click += button_click;
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