zoukankan      html  css  js  c++  java
  • (CSharp)克隆控件事件

     1 // https://stackoverflow.com/questions/6055038/how-to-clone-control-event-handlers-at-run-time
     2 // "C:Program Files (x86)MSBuild14.0Bincsc.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!
    Click btn2 again.");
    31         };
    32         this.Controls.Add(_btn1);
    33         this.Controls.Add(_btn2);
    34         this.Width = 240;
    35         this.Height = 120;
    36     }
    37 }
  • 相关阅读:
    nyoj 228士兵杀敌(五)
    hdu2072 单词数
    nyoj123士兵杀敌(四)(树状数组)
    nyoj1092数字分隔(二)
    HDU1166:敌兵布阵(线段树单点更新,区间查询)
    nyoj269VF(dp)
    nyoj 860又见01背包(01背包)
    poj2184(01背包变形)
    HDU2159FATE(完全背包变形)
    HDU4508 完全背包
  • 原文地址:https://www.cnblogs.com/Bob-wei/p/7281502.html
Copyright © 2011-2022 走看看