C#中删除控件的事件的方法类.
方法一:
代码
/// <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);
}
/// 删除指定控件的指定事件
/// </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事件的所有挂接事件。
方法二,写一个操作类,记录添加的事件列表,删除时从事件列表中读取出来然后删除.
代码