首页 > 其他 > 详细

remove all event handlers from a control

时间:2014-03-29 13:37:00      阅读:454      评论:0      收藏:0      [点我收藏+]

The sample code below will remove all Click events from button1

bubuko.com,布布扣
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]);
        }
    }
}
bubuko.com,布布扣

or

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

or

bubuko.com,布布扣
    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();
    }
bubuko.com,布布扣

remove all event handlers from a control,布布扣,bubuko.com

remove all event handlers from a control

原文:http://www.cnblogs.com/zeroone/p/3632239.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!