How would it be possible to remove all event handlers of the 'Click' event of a 'Button'?

后端 未结 6 623
孤街浪徒
孤街浪徒 2020-11-28 11:56

I have a button control, and I\'d need to remove all the event handlers attached to its Click event.

How would that be possible?

Button button = GetB         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 12:44

    I had the null error issue with the code Jamie Dixon posted to take in to account not having a Click event.

    private void RemoveClickEvent(Control control)
    {
        // chenged "FieldInfo f1 = typeof(Control)" to "var f1 = b.GetType()". By changing to 
        // the type of the  passed in control we can use this for any control with a click event.
        // using var allows for null checking and lowering the chance of exceptions.
    
        var fi = control.GetType().GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic);
        if (fi != null)
        {
            object obj = fi.GetValue(control);
            PropertyInfo pi = control.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
            EventHandlerList list = (EventHandlerList)pi.GetValue(control, null);
            list.RemoveHandler(obj, list[obj]);
        }
    
    }
    

    Then a small change and it should be for any event.

    private void RemoveClickEvent(Control control, string theEvent)
    {
        // chenged "FieldInfo f1 = typeof(Control)" to "var f1 = b.GetType()". By changing to 
        // the type of the  passed in control we can use this for any control with a click event.
        // using var allows for null checking and lowering the chance of exceptions.
    
        var fi = control.GetType().GetField(theEvent, BindingFlags.Static | BindingFlags.NonPublic);
        if (fi != null)
        {
            object obj = fi.GetValue(control);
            PropertyInfo pi = control.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
            EventHandlerList list = (EventHandlerList)pi.GetValue(control, null);
            list.RemoveHandler(obj, list[obj]);
        }
    
    }
    

    I imagine this could be made better but it works for my current need. Hope this is useful for someone.

提交回复
热议问题