纸上得来终觉浅,绝知此事要躬行。

 

批量清除为Button注册的事件

要判断Button.Click是否已经绑定了Click只能去Button的EventHandlerList里面找

事实上, C#的Control封装了EventHandlerList, 但它是protected的, 所以我们不能简单的看到它的存在, 不过, 如果你走Debug Mode的话, 还是可以看得很清楚的, 但如果真要把它拿出来用, 就只能用Reflect了

PropertyInfo propertyInfo = (typeof(System.Windows.Forms.Button)).GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
EventHandlerList eventHandlerList = (EventHandlerList)propertyInfo.GetValue(btn1, 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())
    {
        Console.WriteLine(temp.Method.Name);
        //这个地方可以清除所有的委托,也可以使用条件清除指定委托,没有办法直接清除所有的
    }
}

posted on 2012-05-15 19:53  JRoger  阅读(430)  评论(0编辑  收藏  举报

导航