如何从控件中删除所有事件处理程序 [英] 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?
推荐答案
我在 MSDN论坛。以下示例代码将从 button1
中删除所有单击
事件。
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屋!
查看全文