您的位置:首页 > 其它

How to remove all event handlers from a control

2011-11-06 12:45 471 查看
public partial class Form1:Form
{
publicForm1()
{
InitializeComponent();

button1.Click+= button1_Click;
button1.Click+= button1_Click2;
button2.Click+= button2_Click;
}

privatevoid button1_Click(object sender,EventArgs e)
{
MessageBox.Show("Hello");
}

privatevoid button1_Click2(object sender,EventArgs e)
{
MessageBox.Show("World");
}

privatevoid button2_Click(object sender,EventArgs e)
{
RemoveClickEvent(button1);
}

privatevoidRemoveClickEvent(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]);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: