我坐在我的电脑前想知道如何获得所有添加的事件。我刚刚阅读了一些文章,包括AC# Bedtime Story以更好地理解事件,我认为我现在明白了主要思想。但是我仍然不知道如何获取在触发事件时执行的方法/委托的列表。实际上,就我而言,如果我知道是否将任何方法/委托分配给某个事件就足够了。例如:我正在使用Gma.UserActivityMonitor
(用于键盘/鼠标挂钩)现在我想知道事件HookManager.KeyUp
事件是否不为空。如果为空,则添加代表喊声。在我的情况下这个\ /
HookManager.KeyUp += new KeyEventHandler(HookManager_KeyUp);
编辑
示例代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using Gma.UserActivityMonitor;
namespace EventTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
HookManager.KeyUp += new KeyEventHandler(HookManager_KeyUp);
Delegate[] a = GetEventSubscribers(button1, "Click");
label1.Text = a[0].Method.ToString();
}
void HookManager_KeyUp(object sender, KeyEventArgs e)
{
/* Do something*/
}
bool NoEventAttached()
{
return false;
}
public static Delegate[] GetEventSubscribers(object target, string eventName)
{
Type t = target.GetType();
var eventInfo = t.GetEvent(eventName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
do
{
FieldInfo[] fia = t.GetFields(
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.NonPublic);
foreach (FieldInfo fi in fia)
{
if (fi.Name == eventName)
{
Delegate d = fi.GetValue(target) as Delegate;
if (d != null)
return d.GetInvocationList();
}
else if (fi.FieldType == typeof(EventHandlerList))
{
----> var obj = fi.GetValue(target) as EventHandlerList;
var eventHandlerFieldInfo = obj.GetType().GetField("head", BindingFlags.Instance | BindingFlags.NonPublic);
do
{
var listEntry = eventHandlerFieldInfo.GetValue(obj);
var handler = listEntry.GetType().GetField("handler", BindingFlags.Instance | BindingFlags.NonPublic);
if (handler != null)
{
var subD = handler.GetValue(listEntry) as Delegate;
if (subD.GetType() != eventInfo.EventHandlerType)
{
eventHandlerFieldInfo = listEntry.GetType().GetField("next", BindingFlags.Instance | BindingFlags.NonPublic);
obj = listEntry as EventHandlerList; <-----------
continue;
}
if (subD != null)
{
return subD.GetInvocationList();
}
}
}
while (eventHandlerFieldInfo != null);
}
}
t = t.BaseType;
} while (t != null);
return new Delegate[] { };
}
private void button1_Click(object sender, EventArgs e)
{
}
private void button1_MouseClick(object sender, MouseEventArgs e)
{
}
}
}