How to remove all event handlers from an event

后端 未结 18 1651
再見小時候
再見小時候 2020-11-22 01:20

To create a new event handler on a control you can do this

c.Click += new EventHandler(mainFormButton_Click);

or this

c.Cli         


        
18条回答
  •  时光取名叫无心
    2020-11-22 01:55

    Sometimes we have to work with ThirdParty controls and we need to build these awkward solutions. Based in @Anoop Muraleedharan answer I created this solution with inference type and ToolStripItem support

        public static void RemoveItemEvents(this T target, string eventName) 
            where T : ToolStripItem
        {            
            RemoveObjectEvents(target, eventName);
        }
    
        public static void RemoveControlEvents(this T target, string eventName)
            where T : Control
        {
            RemoveObjectEvents(target, eventName);
        }
    
        private static void RemoveObjectEvents(T target, string Event) where T : class
        {
            var typeOfT = typeof(T);
            var fieldInfo = typeOfT.BaseType.GetField(
                Event, BindingFlags.Static | BindingFlags.NonPublic);
            var provertyValue = fieldInfo.GetValue(target);
            var propertyInfo = typeOfT.GetProperty(
                "Events", BindingFlags.NonPublic | BindingFlags.Instance);
            var eventHandlerList = (EventHandlerList)propertyInfo.GetValue(target, null);
            eventHandlerList.RemoveHandler(provertyValue, eventHandlerList[provertyValue]);
        }
    

    And you can use it like this

        var toolStripButton = new ToolStripButton();
        toolStripButton.RemoveItemEvents("EventClick");
    
        var button = new Button();
        button.RemoveControlEvents("EventClick");
    

提交回复
热议问题