2 つのユーザー コントロールがあり、コントロールの 1 つのインスタンスからイベント ハンドラーを削除したいとします。
説明するために、ユーザー コントロールとしてボタンを作成しました。
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;
}
}
フォームに 2 つのスーパー ボタンを追加しました。SuperButton2 の MouseEnter イベントの発生を無効にしたいと考えています。
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;
更新:このコメントの質問を読んでください...