0

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...

4

2 回答 2

2

In your case, you don't need to remove all event handlers at once, just the specific one you're interested in. Use -= to remove a handler in the same way you use += to add one:

button1.MouseEnter -= button1_MouseEnter;
于 2012-08-14T04:09:53.510 回答
1

Why not just set superButton2.MouseEnter = null;? That should do the trick until somewhere MouseEnter is assigned a value.

Just for an update, another way to handle it, and perfectly legal :)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace TestControls
{
    class SimpleButton:Button
    {
        public bool IgnoreMouseEnter { get; set; }

        public SimpleButton()
        {
            this.IgnoreMouseEnter = false;
        }

        protected override void OnMouseEnter(EventArgs e)
        {
            Debug.Print("this.IgnoreMouseEnter = {0}", this.IgnoreMouseEnter);

            if (this.IgnoreMouseEnter == false)
            {
                base.OnMouseEnter(e);
            }
        }
    }
}
于 2012-08-14T04:03:04.383 回答