• 动态调用事件,事件的方法


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

  • 相关阅读:
    使用 Vim 搭建 JavaScript 开发环境
    SpaceVim 语言模块 erlang
    SpaceVim 语言模块 lua
    SpaceVim 语言模块 python
    SpaceVim 语言模块 elixir
    SpaceVim 语言模块 dart
    SpaceVim 语言模块 elm
    如何配置 SpaceVim
    彻底理解浏览器缓存机制
    react-创建react元素
  • 原文地址:https://www.cnblogs.com/mingyongcheng/p/3455401.html
Copyright © 2020-2023  润新知