C# 清除控件的所有事件委託

/// <summary>
        /// 獲取控件事件  
        /// </summary>
        /// <param name="p_Control">對象</param>
        /// <param name="p_EventName">事件名 EventClick EventDoubleClick </param>
        /// <returns>委託列</returns>
        public Delegate[] GetObjectEventList(ToolStripItem p_Control, string p_EventName)
        {
            PropertyInfo _PropertyInfo = p_Control.GetType().GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
            if (_PropertyInfo != null)
            {
                object _EventList = _PropertyInfo.GetValue(p_Control, null);
                if (_EventList != null && _EventList is EventHandlerList)
                {
                    EventHandlerList _List = (EventHandlerList)_EventList;
                    FieldInfo _FieldInfo = (typeof(ToolStripItem)).GetField(p_EventName, BindingFlags.Static | BindingFlags.NonPublic);
                    if (_FieldInfo == null) return null;
                    Delegate _ObjectDelegate = _List[_FieldInfo.GetValue(p_Control)];
                    if (_ObjectDelegate == null) return null;
                    return _ObjectDelegate.GetInvocationList();
                }
            }
            return null;
        }
//有重複的事件就清除
                    var EventList = GetObjectEventList(item, "EventClick");
                    if (EventList != null)
                    {
                        foreach (Delegate del in EventList)
                        {
                            typeof(ToolStripItem).GetEvent("Click").RemoveEventHandler(item, del);
                        }
                    }

GetField的時候在原來的Name前面加"Event"前綴

GetField  GetValue 的參數類型是Object類型 可根據具體情況傳入不同控件類型

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