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

来源:互联网 发布:淘宝学院培训图片 编辑:程序博客网 时间:2024/05/17 06:05
/// <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类型 可根据具体情况传入不同控件类型

原创粉丝点击