說我有兩個用戶控件,我想從控件的一個實例中刪除一個事件處理程序。從用戶控件中刪除單個事件處理程序
爲了說明我剛纔提出一個按鈕爲用戶控件:
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