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");
    }
    }
    }

  • 相关阅读:
    RabbitMq安装笔记
    SpringBoot笔记--Jackson
    SpringBoot笔记--FastJson
    由一个“两次请求”引出的Web服务器跨域请求访问问题的解决方案
    转:SpringMVC之类型转换Converter(GenericConverter)
    npm 命令
    数据分页技巧
    Mongo 开发笔记
    Android 开发
    Bash 笔记
  • 原文地址:https://www.cnblogs.com/mingyongcheng/p/3455401.html
Copyright © 2011-2022 走看看