从用户控件中删除单个事件处理程序

时间:2012-08-14 04:00:02

标签: c# events user-controls

假设我有两个用户控件,我想从一个控件实例中删除一个事件处理程序。

为了说明我刚刚将其设为按钮作为用户控件:

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;
}
}

我在表单中添加了两个超级按钮,我想禁用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;

更新:阅读此评论问题...

2 个答案:

答案 0 :(得分:2)

在您的情况下,您不需要一次删除所有事件处理程序,只需要删除您感兴趣的特定事件处理程序。使用-=删除同一个处理程序使用+=添加一个的方式:

button1.MouseEnter -= button1_MouseEnter;

答案 1 :(得分:1)

为什么不设置superButton2.MouseEnter = null;?这应该是技巧,直到MouseEnter被赋予一个值。

只是为了更新,另一种处理它的方式,并且完全合法:)

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);
            }
        }
    }
}
相关问题