尝试"Validating"
而不是"gridControl1.Validating"
“
var eventinfo = FoundControls[0].GetType().GetEvent(
"Validating",
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
尽管这与您已将事件处理程序附加到事件这一事实无关。您正在获取事件本身,而不是附加的处理程序。您不能对eventInfo
变量做任何有用的事情(除了添加和删除其他事件处理程序)。
要访问附加的处理程序(底层委托),您需要查看事件实现的代码(使用像Reflector或dotPeek这样的反编译器,或使用Microsoft Reference Source):
public event CancelEventHandler Validating
{
add
{
base.Events.AddHandler(EventValidating, value);
}
remove
{
base.Events.RemoveHandler(EventValidating, value);
}
}
事实证明,Control
该类使用名为Events
type的属性EventHandlerList
来存储基于键(EventValidating
在本例中为字段)的所有委托。
要检索事件的委托,我们应该从Events
属性中读取它们:
public static Delegate[] RetrieveControlEventHandlers(Control c, string eventName)
{
Type type = c.GetType();
FieldInfo eventKeyField = GetStaticNonPublicFieldInfo(type, "Event" + eventName);
if (eventKeyField == null)
{
eventKeyField = GetStaticNonPublicFieldInfo(type, "EVENT_" + eventName.ToUpper());
if (eventKeyField == null)
{
// Not all events in the WinForms controls use this pattern.
// Other methods can be used to search for the event handlers if required.
return null;
}
}
object eventKey = eventKeyField.GetValue(c);
PropertyInfo pi = type.GetProperty("Events",
BindingFlags.NonPublic | BindingFlags.Instance);
EventHandlerList list = (EventHandlerList)pi.GetValue(c, null);
Delegate del = list[eventKey];
if (del == null)
return null;
return del.GetInvocationList();
}
// Also searches up the inheritance hierarchy
private static FieldInfo GetStaticNonPublicFieldInfo(Type type, string name)
{
FieldInfo fi;
do
{
fi = type.GetField(name, BindingFlags.Static | BindingFlags.NonPublic);
type = type.BaseType;
} while (fi == null && type != null);
return fi;
}
和
public static List<Delegate> RetrieveAllAttachedEventHandlers(Control c)
{
List<Delegate> result = new List<Delegate>();
foreach (EventInfo ei in c.GetType().GetEvents())
{
var handlers = RetrieveControlEventHandlers(c, ei.Name);
if (handlers != null) // Does it have any attached handler?
result.AddRange(handlers);
}
return result;
}
最后一个方法将提取附加到控件事件的所有事件处理程序。这包括来自所有类的处理程序(甚至由 winforms 内部附加)。您还可以按处理程序的目标对象过滤列表:
public static List<Delegate> RetrieveAllAttachedEventHandlersInObject(Control c, object handlerContainerObject)
{
return RetrieveAllAttachedEventHandlers(c).Where(d => d.Target == handlerContainerObject).ToList();
}
现在您可以获得gridControl1
定义在中的所有事件处理程序formB
:
RetrieveAllAttachedEventHandlersInObject(gridControl1, formB);