Say I have two user controls and I want to remove an event handler from one instance of the control.
To illustrate I've just made it a button as user control:
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;
}
}
I've added two super buttons to the form and I want to disable the MouseEnter event firing for 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;
}
}
The code runs but it doesn't work - the MouseEnter and Leave events still fire. I'm looking to do something like this:
superButton2.MouseEnter -= xyz.MouseEnter;
Update: Read this comments questions...