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 即可;

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章