2010-11-17 55 views
3

我有一个对象(myObject),我试图找到任何正在侦听该对象的任何事件的东西。查找给定对象的所有侦听器

下面的代码似乎按照预期为使用AddHandler语法创建的侦听器工作;但不会报告使用“句柄”语法创建的侦听器。

编辑︰看来我是不正确的。无论使用AddHandler/Handles语法,此代码都可以工作。但它似乎只适用于该对象的自定义事件。如果myObject是一个控件 - 我永远不会看到Load()事件处理程序;但我会看到“MyCustomEvent”的处理程序。

任何人都可以告诉我我需要做些什么来获得这些事件吗?

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 
+0

这也应该处理'Handles'的情况,因为这只是'AddHandler'的语法糖。也许你还没有用相关的'Handles'子句创建一个类的对象? – cdhowie 2010-11-17 19:22:03

回答

1

使用基本类型,您将获得所有事件,但只有那些实际使用包含带有侦听方法的委托的专用支持字段的事件。如果他们不这样做(例如,考虑WPF的路由事件),我认为你运气不好:因为custom events可以有任意的AddHandler,RemoveHandler和RaiseEvent实现,所以我认为没有通用的方式来获取监听方法列表(因为可能没有这样的列表)。

0

明白了 - 我的不好。

我所要做的就是调用与对象的基类型相同的子。