Before you start asking why in the world I want to do this, bear in mind I don't have much experience with Windows.Forms and at this point I am just experimenting.
Let's say I form with 5 buttons. And like every button, it should do something once I press it. I found out I could add multiple methods to an event such as this:
button1.Click += DoThis;
button1.Click += ButAlsoThis;
I did this for every button. Then I tried to make a method that removes all methods for a given button. Something like this:
public void RemoveHandlers(Button btn)
{
//Code to remove handlers
}
That's where I got stuck...
I was hoping C# would accept something like this:
btn.Click = null
But appearantly Events only accept '+=' and '-='.
So now I have this elaborate system where I have buttons and an list of EventHandlers, linked with a dictionairy. Then I remove each Eventhandler individually. It works... But I think there should be an easier way.
So long story short:
Is there an easy method to remove all handlers from an Event without prior knowledge of the handlers involved?
Edit, I found the answer thanks to Carlos Landeras:
private void RemoveClickEvent(Button b)
{
FieldInfo f1 = typeof(Control).GetField("EventClick",
BindingFlags.Static | BindingFlags.NonPublic);
object obj = f1.GetValue(b);
PropertyInfo pi = b.GetType().GetProperty("Events",
BindingFlags.NonPublic | BindingFlags.Instance);
EventHandlerList list = (EventHandlerList)pi.GetValue(b, null);
list.RemoveHandler(obj, list[obj]);
}
But I just don't want to copy+paste, I'd like to know what is happening here.