(CSharp)克隆控件事件

 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 }

 

转载于:https://www.cnblogs.com/Bob-wei/p/7281502.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值