删除特定控件的所有事件处理程序 [英] remove all EventHandlers of a specific Control
问题描述
我正在用 winForm 编写应用程序.我在 from1 中有一个面板,它有很多事件处理程序.当我处理 panel1 并创建新 panel 时,以前的事件存在&他们开火.为了删除 panel1 事件,我尝试了下面的代码.
I'm writing an application in winForm. I have a panel in from1 and it has many event handler. When I dispose panel1 and create new panel , the previous events exist & they fire. For removing panel1 events I have tryed code below.
panel1.Click -= clickHandle_1 ;
但它并不适用于程序代码中的每个地方.例如在另一种方法中.创建新的 panel1 时,如何删除 panel1 之前的所有事件?
But it doesn't work every where in program code. for example in another method. How can I remove all previous events of panel1 when I create new panel1 ?
推荐答案
根据 这个,要取消 panel1 的所有点击事件,请执行以下操作:
According to this, for cancelling all Click Events of panel1 do this:
FieldInfo f1 = typeof(Control).GetField("EventClick", BindingFlags.Static| BindingFlags.NonPublic);
object obj = f1.GetValue(panel1);
PropertyInfo pi = panel1.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
EventHandlerList list = (EventHandlerList)pi.GetValue(panel1, null);
list.RemoveHandler(obj, list[obj]);
为了取消 panel1 的其他事件,请将 EventClick
更改为要删除的事件名称.
And for cancelling other events of panel1 change EventClick
to event name that you want to remove.
可以使用此代码获取所有事件名称:
One can get all event names using this code:
EventInfo[] info = type.GetEvents();
for (int i = 0; i < info.Length; i++)
{
Console.WriteLine(info[i].Name + "\n");
}
这篇关于删除特定控件的所有事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!