How to remove all event handlers from an event

后端 未结 18 1637
再見小時候
再見小時候 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:33

    Wow. I found this solution, but nothing worked like I wanted. But this is so good:

    EventHandlerList listaEventos;
    
    private void btnDetach_Click(object sender, EventArgs e)
    {
        listaEventos = DetachEvents(comboBox1);
    }
    
    private void btnAttach_Click(object sender, EventArgs e)
    {
        AttachEvents(comboBox1, listaEventos);
    }
    
    public EventHandlerList DetachEvents(Component obj)
    {
        object objNew = obj.GetType().GetConstructor(new Type[] { }).Invoke(new object[] { });
        PropertyInfo propEvents = obj.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
    
        EventHandlerList eventHandlerList_obj = (EventHandlerList)propEvents.GetValue(obj, null);
        EventHandlerList eventHandlerList_objNew = (EventHandlerList)propEvents.GetValue(objNew, null);
    
        eventHandlerList_objNew.AddHandlers(eventHandlerList_obj);
        eventHandlerList_obj.Dispose();
    
        return eventHandlerList_objNew;
    }
    
    public void AttachEvents(Component obj, EventHandlerList eventos)
    {
        PropertyInfo propEvents = obj.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
    
        EventHandlerList eventHandlerList_obj = (EventHandlerList)propEvents.GetValue(obj, null);
    
        eventHandlerList_obj.AddHandlers(eventos);
    }
    

提交回复
热议问题