WinForm/C# C# 控件如何获取事件已经注册的方法

wangqingjie · 2016年09月01日 · 126 次阅读

我们通过反射的机制可以访问到控件事件注册的方法。

示例代码如下:

public partial class Form1 : Form
    {
        private Button btnDemo;
        public Form1()
        {
            InitializeComponent();

            btnDemo = new Button();
            btnDemo.Click += btnDemo_Click;
            btnDemo.Click += btnDemo_Click;
            btnDemo.Click += btnDemo_Click1;

            /* 下面的代码是用来获取btnDemo的Click事件注册的方法的 */
            PropertyInfo propertyInfo = btnDemo.GetType().GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
            if (propertyInfo == null) { return; }

            EventHandlerList eventList = (EventHandlerList)propertyInfo.GetValue(btnDemo, null);
            FieldInfo fieldInfo = typeof(Control).GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic);
            if (fieldInfo == null) { return; }

            Delegate delegateInfo = eventList[fieldInfo.GetValue(btnDemo)];
            if (delegateInfo == null) { return; }
            Delegate[] delegateList = delegateInfo.GetInvocationList();

            foreach (Delegate dInfo in delegateList)
            {
                MessageBox.Show(dInfo.Method.Name);
            }
        }


        private void btnDemo_Click(object sender, EventArgs e)
        { }

        private void btnDemo_Click1(object sender, EventArgs e)
        { }
    }

执行上段代码的数据结果依次为:

btnDemo_Click
btnDemo_Click
btnDemo_Click1

暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册