On Sun, 2 Oct 2005 20:34:56 -0700, "Franco, Gustavo"
<gustavo_franco[REMOVEIT]@hotmail.com> wrote:
How can it be done?
Try this:
// ********* USE THIS FOR INSTANCE EVENTS ********
// Replace "handler" with the events name
// Replace instance with the object holding the event
//Get eventinfo object so we can call Remove method directly
EventInfo info = instance.GetType().GetEvent("handler");
//"Free" eventhandler so we can call call GetInvocationList
FieldInfo field = instance.GetType().GetField( "handler",
BindingFlags.NonPublic | BindingFlags.Instance );
EventHandler eh = field.GetValue(instance) as EventHandler;
//Remove events one by one
foreach(Delegate del in eh.GetInvocationList())
info.GetRemoveMethod().Invoke(instance, new object[] { del });
// ********* USE THIS FOR STATIC EVENTS ********
// Replace handlerStatic with the events name
// Replace MyClass with the class containing the event
//Get eventinfo object so we can call Remove method directly
EventInfo info2 = typeof(MyClass).GetEvent("handlerStatic");
//"Free" eventhandler so we can call call GetInvocationList
FieldInfo field2 = typeof(MyClass).GetField("handlerStatic",
BindingFlags.NonPublic | BindingFlags.Static);
EventHandler eh2 = field2.GetValue(null) as EventHandler;
//Remove events one by one
foreach (Delegate del in eh2.GetInvocationList())
info2.GetRemoveMethod().Invoke(null, new object[] { del });
Using reflection to remove unknown Events is the only way since it is
impossible to access the EventHandlers methods outside the declaring
class otherwise.
Hopefully this should work in most cases. I have only tested it
briefly.
--
Marcus Andrén