I have an object (myObject) and I'm trying to find everything that is listening to any event of that object.
The following code seems to work as expected for listeners created with the AddHandler syntax; but does not report listeners created using the 'Handles' syntax.
EDIT: It appears I was incorrect. This code does work, regardless of AddHandler/Handles syntax; but it only seems to work for custom events of the object. If myObject is a control - I never see the Load() event handlers; but I will see handlers for 'MyCustomEvent'.
Can anyone tell me what I'd need to do to get those events as well?
Public Sub GetListeners(ByVal myObject As Object)
Dim myType As Type = myObject.GetType
Dim myFieldList As FieldInfo() = myType.GetFields(BindingFlags.Static Or BindingFlags.Instance Or BindingFlags.NonPublic)
For Each myInfo In myFieldList
Dim myDelegate As [Delegate] = TryCast(myInfo.GetValue(myObject), [Delegate])
If myDelegate IsNot Nothing Then
For Each myItem In myDelegate.GetInvocationList
System.Diagnostics.Debug.WriteLine(myDelegate.GetInvocationList(0).Method.Name & "-->" & myDelegate.GetInvocationList(0).Method.DeclaringType.FullName)
Next
End If
Try
Dim eventList As EventHandlerList = DirectCast(myObject.GetType().GetProperty("Events", _
(BindingFlags.FlattenHierarchy Or (BindingFlags.NonPublic Or BindingFlags.Instance))).GetValue(myObject, Nothing), EventHandlerList)
myDelegate = eventList(myInfo.GetValue(myObject))
Catch ex As Exception
End Try
If myDelegate IsNot Nothing Then
For Each myItem In myDelegate.GetInvocationList
System.Diagnostics.Debug.WriteLine(myDelegate.GetInvocationList(0).Method.Name & "-->" & myDelegate.GetInvocationList(0).Method.DeclaringType.FullName)
Next
End If
Next
End Sub
Using the base types, you will get all events, but only those which actually use a private backing field containing the delegate with the listening methods. If they don't do this (consider, for example, the routed events of WPF), I think you are out of luck: Since custom events can have an arbitrary implementation of AddHandler, RemoveHandler and RaiseEvent, I don't think there is a generic way to get a list of listening methods (because there might not be such a list).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With