3

我正在跟踪是否触发了这样的事件:

bool IsFormLoaded;
private void Form1_Load(object sender, EventArgs e)
{
    //Do stuff
    IsFormLoaded = true;
}
private void button1_Click(object sender, EventArgs e)
{
    //Do stuff
}

但是对许多事件这样做并不优雅,所以我想要一个解决方案,让我检查是否有任何事件像这样被触发:

bool IsFormLoaded = IsEventFired(Form1_Loaded);
bool IsButton1Clicked = IsEventFired(Button1_Click);
4

4 回答 4

5

您正在使用设计器处理事件。例如,您可以在构造函数中执行此操作,如下所示:

this.Load += delegate { IsFormLoaded = true; };
button1.Click += delegate { IsButton1Clicked = true; };

IMO 它更优雅:)

于 2013-01-08T14:24:19.070 回答
1

有趣的问题,在我看来就像你不想一遍又一遍地写的东西。这就是为什么我宁愿选择一个通用组件,而不是一个哈希集或类似的东西。此外,由于表单实现通常基于线程,因此我使用并发字典。

可以通过几种不同的方式改进此解决方案;最明显的是使处理更加通用,并且缺少 0 参数处理程序。为了清关,我尽可能简单。也许我会在几天后在我的博客上发布更完整的内容;如果我这样做,我会在这里分享信息。

我的解决方案有 2 个部分:(1) 通用钩子类和 (2) 表单中的实现。目前解决方案是懒惰的,例如我把事件处理程序放在最后,而不是放在队列的前面。您应该能够通过使用 GetInvocationList 或类似的东西来解决这个问题。

通用挂钩类基本上挂钩事件并跟踪是否调用了事件:

public class EventHooks
{
    private class EventHooksEquality : IEqualityComparer<Tuple<string, object>>
    {
        public bool Equals(Tuple<string, object> x, Tuple<string, object> y)
        {
            return x.Item1.Equals(y.Item1) && object.ReferenceEquals(x.Item2, y.Item2);
        }

        public int GetHashCode(Tuple<string, object> obj)
        {
            return obj.Item1.GetHashCode();
        }
    }

    private ConcurrentDictionary<Tuple<string, object>, bool> called =
        new ConcurrentDictionary<Tuple<string, object>, bool>(new EventHooksEquality());

    private abstract class BaseHookHandler
    {
        protected BaseHookHandler(object container, string eventName, EventHooks hooks)
        {
            this.hooks = hooks;
            this.container = container;
            this.eventName = eventName;
        }

        protected string eventName;
        protected object container;
        protected EventHooks hooks;
    }

    private class HookHandler<T1> : BaseHookHandler
    {
        public HookHandler(object container, string eventName, EventHooks hooks)
            : base(container, eventName, hooks)
        {
        }
        public void Handle(T1 t1)
        {
            hooks.called.TryAdd(new Tuple<string, object>(eventName, container), true);
        }
    }

    private class HookHandler<T1, T2> : BaseHookHandler
    {
        public HookHandler(object container, string eventName, EventHooks hooks)
            : base(container, eventName, hooks)
        {
        }
        public void Handle(T1 t1, T2 t2)
        {
            hooks.called.TryAdd(new Tuple<string, object>(eventName, container), true);
        }
    }
    // add more handlers here...

    public void HookAll(object obj)
    {
        foreach (var eventHandler in obj.GetType().GetEvents()) 
        {
            Hook(obj, eventHandler.Name);
        }
    }

    public void Hook(object obj, string eventHandler)
    {
        if (obj == null)
        {
            throw new Exception("You have to initialize the object before hooking events.");
        }

        // Create a handler with the right signature
        var field = obj.GetType().GetEvent(eventHandler);
        var delegateInvoke = field.EventHandlerType.GetMethod("Invoke");
        Type[] parameterTypes = delegateInvoke.GetParameters().Select((a) => (a.ParameterType)).ToArray();

        // Select the handler with the correct number of parameters
        var genericHandler = Type.GetType(GetType().FullName + "+HookHandler`" + parameterTypes.Length);
        var handlerType = genericHandler.MakeGenericType(parameterTypes);
        var handlerObject = Activator.CreateInstance(handlerType, obj, eventHandler, this);
        var handler = handlerType.GetMethod("Handle");

        // Create a delegate
        var del = Delegate.CreateDelegate(field.EventHandlerType, handlerObject, handler);

        // Add the handler to the event itself
        field.AddEventHandler(obj, del);
    }

    public bool IsCalled(object obj, string eventHandler)
    {
        return called.ContainsKey(new Tuple<string, object>(eventHandler, obj));
    }
}

类中的用法可以按如下方式进行(示例):

   public Form1()
    {
        InitializeComponent();

        hooks.HookAll(this);
        // or something like: hooks.Hook(this, "Load");
        hooks.Hook(button1, "Click");

    }

    private EventHooks hooks = new EventHooks();

    private void Form1_Load(object sender, EventArgs e)
    {
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.textBox1.Text = 
            string.Format("Load: {0}\r\nClick: {1}\r\nButton click: {2}\r\n",
            hooks.IsCalled(this, "Load"),
            hooks.IsCalled(this, "Click"),
            hooks.IsCalled(button1, "Click"));
    }
于 2013-01-08T15:31:08.427 回答
0

编写您自己的基本表单(从 Windows.Forms.Form 派生),并覆盖事件触发方法以捕获事件是否被触发。通过拥有一个基类,您将能够在所有表单中重用您的事件监控逻辑。

这是您可以使用的一些示例代码。我在这里只使用了 Loaded 事件。您必须为要监视的所有事件执行此操作。您也可以使用枚举而不是使用常量。希望这可以帮助

        const string OnLoadFired = "OnLoadFired";
        const string OnShownFired = "OnShownFired";
        List<string> eventsFired = new List<string>();

        protected override void OnLoad(EventArgs e)
        {
            if(!eventsFired.Contains(OnLoadFired))
            {
                eventsFired.Add(OnLoadFired);
            }
            base.OnLoad(e);
        }

        public bool IsEventFired(string eventName)
        {
            return eventsFired.Contains(eventName);
        }
于 2013-01-08T14:35:18.103 回答
0

类似于 Dhawalk 的回答。在我写这篇文章之前,我没有看到那个答案。

        private HashSet<string> events = new HashSet<string>();
        private void IsLoaded(object sender, RoutedEventArgs e)
        {
            // check
            System.Diagnostics.Debug.WriteLine(CheckEvents("IsLoaded", true).ToString());
            // add
            System.Diagnostics.Debug.WriteLine(CheckEvents("IsLoaded", false).ToString());
            // check
            System.Diagnostics.Debug.WriteLine(CheckEvents("IsLoaded", true).ToString());
        }

        private bool CheckEvents(string Event, bool CheckAdd)
        {
            // CheckAdd True to check
            // CheckAdd Fasle to add
            bool result = events.Contains(Event);
            if (!result && !CheckAdd) events.Add(Event);
            return result;
        }
于 2013-01-08T15:12:07.980 回答