The other day a colleague asked me how to remove all delegate from the Click event of a Button, I thought for a moment you can do it this way:
public
void
RemoveEvent(Control c)
{
PropertyInfo propertyInfo = ( typeof (System.Windows.Forms.Button)).GetProperty( " Events " , BindingFlags.Instance | BindingFlags.NonPublic);
EventHandlerList eventHandlerList = (EventHandlerList)propertyInfo.GetValue(c, null );
FieldInfo fieldInfo = ( typeof (Control)).GetField( " EventClick " , BindingFlags.Static | BindingFlags.NonPublic);
Delegate d = eventHandlerList[fieldInfo.GetValue( null )];
if (d != null )
{
foreach (Delegate temp in d.GetInvocationList())
{
c.Click -= (EventHandler)temp;
}
}
}
{
PropertyInfo propertyInfo = ( typeof (System.Windows.Forms.Button)).GetProperty( " Events " , BindingFlags.Instance | BindingFlags.NonPublic);
EventHandlerList eventHandlerList = (EventHandlerList)propertyInfo.GetValue(c, null );
FieldInfo fieldInfo = ( typeof (Control)).GetField( " EventClick " , BindingFlags.Static | BindingFlags.NonPublic);
Delegate d = eventHandlerList[fieldInfo.GetValue( null )];
if (d != null )
{
foreach (Delegate temp in d.GetInvocationList())
{
c.Click -= (EventHandler)temp;
}
}
}
The basic principle is done by reflection, processed to obtain a list of fields and then commissioned ( (EventHandlerList) propertyInfo.GetValue (c, null) can get the delegate list ), the following information can be seen by Reflector:
Reproduced in: https: //www.cnblogs.com/vivounicorn/archive/2009/06/24/1510328.html