说我有两个用户控件,我想从控件的一个实例中删除一个事件处理程序。从用户控件中删除单个事件处理程序
为了说明我刚才提出一个按钮为用户控件:
public partial class SuperButton : UserControl
{
public SuperButton()
{
InitializeComponent();
}
private void button1_MouseEnter(object sender, EventArgs e)
{
button1.BackColor = Color.CadetBlue;
}
private void button1_MouseLeave(object sender, EventArgs e)
{
button1.BackColor = Color.Gainsboro;
}
}
我已经添加了两个超级按钮的形式,我想禁用MouseEnter事件烧成SuperButton2。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
superButton2.RemoveEvents<SuperButton>("EventMouseEnter");
}
}
public static class EventExtension
{
public static void RemoveEvents<T>(this Control target, string Event)
{
FieldInfo f1 = typeof(Control).GetField(Event, BindingFlags.Static | BindingFlags.NonPublic);
object obj = f1.GetValue(target.CastTo<T>());
PropertyInfo pi = target.CastTo<T>().GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
EventHandlerList list = (EventHandlerList)pi.GetValue(target.CastTo<T>(), null);
list.RemoveHandler(obj, list[obj]);
}
public static T CastTo<T>(this object objectToCast)
{
return (T)objectToCast;
}
}
代码运行,但它不工作 - 的MouseEnter和Leave事件仍然火灾。我正在寻找这样的事情:
superButton2.MouseEnter - = xyz.MouseEnter;
更新:阅读本评论问题...
'superButton2.MouseEnter - = button1_MouseEnter'不起作用? – 2012-08-14 04:03:16
我需要在Form1中完成它,而不是在用户控件中。除非嗯 – 2012-08-14 04:05:20
@lc - 把这作为一个答案,你可以。如:'public void DisableEvent(){button1.MouseEnter - = button1_MouseEnter;}' – 2012-08-14 04:06:50