C# 控件获取事件已经注册的方法(判断对应的控件有没有对应的事件)

直接上代码了

可以直接用

        /// <summary>
        /// 查找控件的对应的事件注册的方法名
        /// </summary>
        /// <param name="control">控件</param>
        /// <param name="eventName">事件</param>
        /// <returns>返回事件注册的方法名,若未找到则返回null</returns>
        private static string GetBindingMethod(Control control, string eventName)
        {
            //EventInfo info = control.GetType().GetEvent(eventName);

            PropertyInfo propertyInfo = control.GetType().GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
            if (propertyInfo == null) { return null; }

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

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

            return delegateList[delegateList.Length - 1].Method.Name;
        }

如果想判断对应的控件有没有对应的事件;

可以稍微改变一下代码,遍历delegateList 即可;

发布了20 篇原创文章 · 获赞 34 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/feiduan1211/article/details/90106602