如何从控件中移除所有事件处理程序 [英] How to remove all event handlers from a control
本文介绍了如何从控件中移除所有事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
要你能做到这一点的控制创建一个新的事件处理程序
To create a new event handler on a control you can do this
c.Click += new EventHandler(mainFormButton_Click);
或本
c.Click += mainFormButton_Click;
和删除事件处理程序,你可以做到这一点。
and to remove an event handler you can do this
c.Click -= mainFormButton_Click;
但你如何从控制删除所有事件处理程序?
But how do you remove all event handlers from a control?
推荐答案
我发现了一个解决方案,<一个href=\"http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/576f69e7-55aa-4574-8d31-417422954689/\">MSDN论坛。下面的示例code将删除所有点击
事件从按钮1
。
I found a solution on the MSDN forums. 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]);
}
}
}
这篇关于如何从控件中移除所有事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文