方法一:
代碼
/// <summary>
/// 刪除指定控件的指定事件
/// </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);
}
調用:ClearEvent(button1,"Click");//就會清除button1對象的Click事件的所有掛接事件。
方法二,寫一個操作類,記錄添加的事件列表,刪除時從事件列表中讀取出來然後刪除.