1 // https://stackoverflow.com/questions/6055038/how-to-clone-control-event-handlers-at-run-time
2 // "C:\Program Files (x86)\MSBuild\14.0\Bin\csc.exe" /t:winexe /out:cloneevents.exe cloneevents.cs && start "cloneevents.exe" cloneevents.exe
3 using System;
4 using System.ComponentModel;
5 using System.Reflection;
6 using System.Windows.Forms;
7
8 static class Program {
9 [STAThread]
10 public static void Main(params string[] args){
11 Application.Run(new Form1());
12 }
13
14 public static void CloneEvents(Control targetControl, Control activeContorl) {
15 FieldInfo eventsField = typeof(Component).GetField("events", BindingFlags.NonPublic | BindingFlags.Instance);
16 object eventHandlers = eventsField.GetValue(targetControl);
17 eventsField.SetValue(activeContorl, eventHandlers);
18 }
19 }
20
21
22 public class Form1 : Form {
23 Button _btn1= new Button { Text = "btn1", Left = 20, Top = 10, Width = 180 };
24 Button _btn2 = new Button { Text = "clone btn1's click event", Left = 20, Top = 40, Width = 180 };
25
26 public Form1() {
27 _btn1.Click+=(ss,se)=> MessageBox.Show(this, "btn1 is clicked.");
28 _btn2.Click+=(ss,se)=> {
29 Program.CloneEvents(_btn1, _btn2);
30 MessageBox.Show(this, "Clone btn1's events OK!\nClick btn2 again.");
31 };
32 this.Controls.Add(_btn1);
33 this.Controls.Add(_btn2);
34 this.Width = 240;
35 this.Height = 120;
36 }
37 }