我正在跟踪事件是否像这样被触发:
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);
答案 0 :(得分:5)
您正在使用设计师处理事件。例如,您可以在构造函数中执行此操作,如下所示:
this.Load += delegate { IsFormLoaded = true; };
button1.Click += delegate { IsButton1Clicked = true; };
IMO它更优雅:)
答案 1 :(得分:1)
类似于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;
}
答案 2 :(得分:1)
有趣的问题,在我看来,你不想一遍又一遍地写一些东西。这就是为什么我宁愿选择一个通用组件,而不是像hashset那样的东西。此外,由于表单实现通常基于线程,我使用并发字典。
这种解决方案可以通过几种不同的方式进行改进;最明显的是使处理更通用,缺少0参数处理程序。我保持尽可能简单的清理。也许我可能会在几天内在我的博客上发布更完整的内容;如果我这样做,我会在这里分享信息。
我的解决方案有两部分:(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"));
}
答案 3 :(得分: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);
}