(CSharp)克隆控件事件

时间:2023-03-09 22:03:28
(CSharp)克隆控件事件
 // https://*.com/questions/6055038/how-to-clone-control-event-handlers-at-run-time
// "C:\Program Files (x86)\MSBuild\14.0\Bin\csc.exe" /t:winexe /out:cloneevents.exe cloneevents.cs && start "cloneevents.exe" cloneevents.exe
using System;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms; static class Program {
[STAThread]
public static void Main(params string[] args){
Application.Run(new Form1());
} public static void CloneEvents(Control targetControl, Control activeContorl) {
FieldInfo eventsField = typeof(Component).GetField("events", BindingFlags.NonPublic | BindingFlags.Instance);
object eventHandlers = eventsField.GetValue(targetControl);
eventsField.SetValue(activeContorl, eventHandlers);
}
} public class Form1 : Form {
Button _btn1= new Button { Text = "btn1", Left = , Top = , Width = };
Button _btn2 = new Button { Text = "clone btn1's click event", Left = , Top = , Width = }; public Form1() {
_btn1.Click+=(ss,se)=> MessageBox.Show(this, "btn1 is clicked.");
_btn2.Click+=(ss,se)=> {
Program.CloneEvents(_btn1, _btn2);
MessageBox.Show(this, "Clone btn1's events OK!\nClick btn2 again.");
};
this.Controls.Add(_btn1);
this.Controls.Add(_btn2);
this.Width = ;
this.Height = ;
}
}

相关文章