Friday, March 27, 2009

Get List of Event Handlers.

Quite often we would need to get list of Event Handlers of a particular event from outside the Class that has actually implemented it.

Here is a method which allows you to Check if Event Hendlers are added and if so, gives you the list of method name of those handlers.


private static ArrayList GetListOfEventHanlders()
{
ArrayList delgList;
FieldInfo fi = objClassInstance.GetType().GetField("MyEvent",BindingFlags.Instance | BindingFlags.NonPublic);

object handler = fi.GetValue(objClassInstance);
if(handler!=null)
{
delgList = new ArrayList();
MulticastDelegate originalDelegate = handler as System.MulticastDelegate;
Delegate[] originalHandlers = originalDelegate.GetInvocationList();
foreach(Delegate item in originalHandlers)
{
delgList.Add(item.Method.Name);
}
}
else
{
return null;
}
return delgList;
}

For more details do check out this excellent article by Stephen Horsfield at http://blogs.interakting.co.uk/steve/archive/2008/05/19/NET--Hacking-events-and-manipulating-delegates.aspx