I had the need to remove event handlers from a control loaded from a dll that I don't have the code for. Since there doesn't seem to be an 'official' (i.e. supported by public methods of the .NET Framework), I was was able to create a couple extension methods that did exactly that using Reflection.
See this blog post for all the details: Removing an Event from a WinForm ListView control using reflection
Here is a code sample of how to remove the SelectedIndexChanged event (dynamically and without access to the original handler)
//for a UserControl (in fact any control that implements System.ComponentModel.Component)
var userControl = new UserControl();
//we can get the current mapped event handlers
userControl.eventHandlers();
//its signature
userControl.eventHandlers_MethodSignatures();
//remove one by using the static field name
userControl.remove_EventHandler("EVENT_SELECTEDINDEXCHANGED");
//or use this one specifically mapped to the SelectedIndexChanged event
userControl.remove_Event_SelectedIndexChanged
My question is: "is there another way?"
Although my solution works and seems stable, I'm doing internal .NET objects manipulation, so maybe there is a better solution (in 4.0 or 4.5)?
Related posts:
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…