且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#通过反射移除控件eventhandler方法参考

更新时间:2022-08-26 18:54:34

方法一:
去除事件

public static class EventExtension

{
    public static void RemoveEvents(this Control target,string Event)
    {
            FieldInfo f1 = typeof(Control).GetField(Event,BindingFlags.Static | BindingFlags.NonPublic);
            object obj = f1.GetValue(target.CastTo());
            PropertyInfo pi =target.CastTo().GetType().GetProperty("Events",
                BindingFlags.NonPublic | BindingFlags.Instance);
            EventHandlerList list = (EventHandlerList)pi.GetValue(target.CastTo(), null);
            list.RemoveHandler(obj, list[obj]);
    }
}
使用方法:
Button button=new Button();
button.RemoveEvents
URL:http://***.com/questions/91778/how-to-remove-all-event-handlers-from-a-control

来自博客:
http://www.cnblogs.com/z2002m/archive/2011/04/26/2029457.html

方法二
    public static class RemoveCtrlEvent
    {
        public static void RemoveEvents(this Control target, string eventName)
        {
            if (target == null) return;
            if (string.IsNullOrEmpty(eventName)) return;

            BindingFlags bPropertyFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic;//筛选
            BindingFlags fieldFlags = BindingFlags.Static | BindingFlags.NonPublic;
            Type ctrlType = typeof(System.Windows.Forms.Control);
            PropertyInfo pInfo = ctrlType.GetProperty("Events", bPropertyFlags);
            EventHandlerList evtHLst = (EventHandlerList)pInfo.GetValue(target, null);//事件列表
            FieldInfo fieldInfo = (typeof(Control).GetField("Event" + eventName, fieldFlags));
            Delegate d = evtHLst[fieldInfo.GetValue(target)];

            if (d == null) return;
            EventInfo eventInfo = ctrlType.GetEvent(eventName);

            foreach (Delegate dx in d.GetInvocationList())
            {
                //移除已订阅的eventName类型事件
                eventInfo.RemoveEventHandler(target, dx);
            }
        }
    }

来自博客:
http://blog.sina.com.cn/s/blog_6fd674050100oemh.html