zoukankan      html  css  js  c++  java
  • remove all event handlers from a control

    The sample code below will remove all Click events from button1

    public partial class Form1 : Form
    {
            public Form1()
            {
                InitializeComponent();
    
                button1.Click += button1_Click;
                button1.Click += button1_Click2;
                button2.Click += button2_Click;
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                MessageBox.Show("Hello");
            }
    
            private void button1_Click2(object sender, EventArgs e)
            {
                MessageBox.Show("World");
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                RemoveClickEvent(button1);
            }
    
            private void RemoveClickEvent(Button b)
            {
                FieldInfo f1 = typeof(Control).GetField("EventClick", 
                    BindingFlags.Static | BindingFlags.NonPublic);
                object obj = f1.GetValue(b);
                PropertyInfo pi = b.GetType().GetProperty("Events",  
                    BindingFlags.NonPublic | BindingFlags.Instance);
                EventHandlerList list = (EventHandlerList)pi.GetValue(b, null);
                list.RemoveHandler(obj, list[obj]);
            }
        }
    }

    or

    void OnFormClosing(object sender, FormClosingEventArgs e)
    {
        foreach(Delegate d in FindClicked.GetInvocationList())
        {
            FindClicked -= (FindClickedHandler)d;
        }
    }

    or

        Directly no, in large part because you cannot simply set the event to null.
    
        Indirectly, you could make the actual event private and create a property around it that tracks all of the delegates being added/subtracted to it.
    
        Take the following:
    
        List<EventHandler> delegates = new List<EventHandler>();
    
        private event EventHandler MyRealEvent;
    
        public event EventHandler MyEvent
        {
            add
            {
                MyRealEvent += value;
                delegates.Add(value);
            }
    
            remove
            {
                MyRealEvent -= value;
                delegates.Remove(value);
            }
        }
    
        public void RemoveAllEvents()
        {
            foreach(EventHandler eh in delegates)
            {
                MyRealEvent -= eh;
            }
            delegates.Clear();
        }
  • 相关阅读:
    网络通信之 字节序转换原理与网络字节序、大端和小端模式
    [C/C++]大小端字节序转换程序
    面向对象和面向过程的区别
    编译libjpeg
    地形系统lod
    c/c++ 代码中使用sse指令集加速
    个人作品- 蘑菇大战
    个人作品- 几何战争
    Obj格式模型 读取
    各大引擎矩阵的矩阵存储方式 ----行矩阵 or 列矩阵
  • 原文地址:https://www.cnblogs.com/zeroone/p/3632239.html
Copyright © 2011-2022 走看看