Method 1: Code
/// <Summary>
/// Delete the specified event of the specified control
/// </Summary>
/// <Param name = "control"> </param>
/// <Param name = "eventname"> </param>
Public void ClearEvent (System. Windows. Forms. Control control, string eventname)
{
If (control = null) return;
If (string. IsNullOrEmpty (eventname) return;
BindingFlags mPropertyFlags = BindingFlags. Instance | BindingFlags. Public | BindingFlags. Static | BindingFlags. NonPublic;
BindingFlags mFieldFlags = BindingFlags. Static | BindingFlags. NonPublic;
Type controlType = typeof (System. Windows. Forms. Control );
PropertyInfo propertyInfo = controlType. GetProperty ("Events", mPropertyFlags );
EventHandlerList eventHandlerList = (EventHandlerList) propertyInfo. GetValue (control, null );
FieldInfo fieldInfo = (typeof (System. Windows. Forms. Control). GetField ("Event" + eventname, mFieldFlags );
Delegate d = eventHandlerList [fieldInfo. GetValue (control)];
If (d = null) return;
EventInfo eventInfo = controlType. GetEvent (eventname );
Foreach (Delegate dx in d. GetInvocationList ())
EventInfo. RemoveEventHandler (control, dx );
}
Call: ClearEvent (button1, "Click"); // This will clear all hook events of the Click Event of the button1 object.
Method 2: Write an operation class, record the added event list, read the list from the event list during deletion, and then delete it.
Code
Class MyEventManager: IDisposable
{
EventHandlerList eventList = new EventHandlerList ();
Hashtable eventObjectList = new Hashtable ();
Public void AddEvent (Control control, string eventname, EventHandler eventhandler)
{
String keystr = control. Name + eventname;
If (! EventObjectList. Contains (keystr) eventObjectList. Add (keystr, new object ());
Object eventObject = eventObjectList [keystr];
Switch (eventname)
{
Case "Click ":
Control. Click + = eventhandler;
Break;
Case "Enter ":
Control. Enter + = eventhandler;
Break;
//...
// More event support can be added here, because C # does not support macro replacement.
// Of course, reflection can also be used, but reflection does not need to be used.
}
EventList. AddHandler (eventObject, eventhandler );
}
Public void DelEvent (Control control, string eventname)
{
String keystr = control. Name + eventname;
Object eventObject = eventObjectList [keystr];
Delegate d = eventList [eventObject];
If (d = null) return;
Foreach (Delegate dd in d. GetInvocationList ())
{
Switch (eventname)
{
Case "Click ":
Control. Click-= (EventHandler) dd;
Break;
Case "Enter ":
Control. Enter-= (EventHandler) dd;
Break;
//...
// More event support can be added here, because C # does not support macro replacement.
// Of course, reflection can also be used, but reflection does not need to be used.
}
}
EventList. RemoveHandler (eventObject, d );
EventObjectList. Remove (eventObject );
}
}