0

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;

更新:このコメントの質問を読んでください...

4

2 に答える 2

2

あなたの場合、すべてのイベント ハンドラーを一度に削除する必要はありません。関心のある特定のイベント ハンドラーだけを削除します。ハンドラーを追加する-=場合と同じ方法で、ハンドラーを削除するために使用します。+=

button1.MouseEnter -= button1_MouseEnter;
于 2012-08-14T04:09:53.510 に答える
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);
            }
        }
    }
}
于 2012-08-14T04:03:04.383 に答える