• 如何判断某个事件已经绑定了某个事件处理程序?


    btn.Click += new EventHandler(button2_Click);
    //获取Button类定义的所有事件的信息
    PropertyInfo pi =
    (typeof(Button)).GetProperty("Events", BindingFlags.Instance |BindingFlags.NonPublic); //获取Button对象btn的事件处理程序列表
    EventHandlerList ehl =
    (EventHandlerList)pi.GetValue(btn,null);//获取Control类Click事件的字段信息
    FieldInfo fieldInfo =
    (typeof(Control)).GetField("EventClick", BindingFlags.Static |BindingFlags.NonPublic); //用获取的Click事件的字段信息,去匹配btn对象的事件处理程序列表,获取btn对象Click事件的委托对象 //事件使用委托定义的,C#中的委托时多播委托,可以绑定多个事件处理程序,当事件发生时,这些事件处理程序被依次执行
    //是否已经绑定了事件
    private bool IsBindEvent(Type type, Control con, string eventName)
    {
        bool isBind = false;
    
        PropertyInfo pi = type.GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);   //获取type类定义的所有事件的信息
        EventHandlerList ehl = (EventHandlerList)pi.GetValue(con, null);    //获取con对象的事件处理程序列表
        FieldInfo fieldInfo = (typeof(Control)).GetField("EventText", BindingFlags.Static | BindingFlags.NonPublic); //获取Control类Click事件的字段信息
        Delegate d = ehl[fieldInfo.GetValue(null)];
        if (d == null)
        {
            return isBind;
        }
        foreach (Delegate del in d.GetInvocationList())
        { 
            if (del.Method.Name == eventName)
            {
                isBind = true;
                break;
            }
        }
        return isBind;
    }
    使用示例
    
    var isBind = IsBindEvent(comboBox.GetType(), comboBox, "comboBox_TextChanged");
    
    if (!isBind)
    
    {
    
    comboBox.TextChanged += comboBox_TextChanged;
    
    }
  • 相关阅读:
    还有更简单的不重复随机数生成方法吗?
    SqlServer数据插入性能小记
    html页面滚动时元素错位解决方案
    为Web页中的Table对象创建一个映射表
    js实现的快速排序
    webkit内核的浏览器为什么removeAttribute('style')会失效?
    setAttribute第三个参数
    Windows转到linux中,文件乱码,文件编码转换
    查看端口的占用
    sndfile
  • 原文地址:https://www.cnblogs.com/shiningrise/p/5814218.html
Copyright © 2020-2023  润新知