zoukankan      html  css  js  c++  java
  • 动态调用事件,事件的方法

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;
    using System.Reflection;
    using System.ComponentModel;

    namespace WindowsFormsApplication12
    {
    static class Program
    {
    /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    //[STAThread]
    //static void Main()
    //{
    // Application.EnableVisualStyles();
    // Application.SetCompatibleTextRenderingDefault(false);
    // //Application.Run(new Form1());
    //}


    static void Main(string[] args)
    {
    System.Windows.Forms.Button btn = new System.Windows.Forms.Button();
    System.Windows.Forms.Button btn1 = new System.Windows.Forms.Button();
    btn.Click += new EventHandler(btn_Click);
    btn.Click += new EventHandler(btn_Click2);
    btn.Click += new EventHandler(btn_Click3);
    ChangeDelegate(btn, btn1);
    btn1.PerformClick();

    }

    private static void ChangeDelegate(System.Windows.Forms.Button btn, System.Windows.Forms.Button btn1)
    {
    Type type = btn.GetType();
    PropertyInfo pi = type.GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
    EventHandlerList ehl = (EventHandlerList)pi.GetValue(btn, null);
    FieldInfo fieldInfo = (typeof(System.Windows.Forms.Control)).GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic);
    Delegate d = ehl[fieldInfo.GetValue(null)];
    foreach (Delegate del in d.GetInvocationList())
    {
    btn1.Click += (EventHandler)del;
    System.Diagnostics.Debug.WriteLine(del.Method.Name);
    //type.InvokeMember("EventClick", BindingFlags.Default | BindingFlags.InvokeMethod, null, btn, new object[] { });
    }
    }

    static void btn_Click(object sender, EventArgs e)
    {
    System.Diagnostics.Debug.WriteLine("Click1");
    }

    static void btn_Click2(object sender, EventArgs e)
    {
    Console.WriteLine("Click2");
    }

    static void btn_Click3(object sender, EventArgs e)
    {
    Console.WriteLine("Click3");
    }
    }
    }

  • 相关阅读:
    『Nltk』常用方法
    『Kaggle』分类任务_决策树&集成模型&DataFrame向量化操作
    『Pandas』数据读取&DataFrame切片
    『TensotFlow』RNN中文文本_下_暨研究生开学感想
    『Scrapy』爬取斗鱼主播头像
    『Scrapy』爬取腾讯招聘网站
    『TensorFlow』梯度优化相关
    『Scrapy』终端调用&选择器方法
    『Scrapy』全流程爬虫demo
    使用VS2013、TFS2013和Git进行分布式团队协作
  • 原文地址:https://www.cnblogs.com/mingyongcheng/p/3455401.html
Copyright © 2011-2022 走看看