代码之家  ›  专栏  ›  技术社区  ›  Jeff

在.NET中查找Windows窗体控件的所有事件处理程序

  •  2
  • Jeff  · 技术社区  · 15 年前

    是否有方法查找 Windows Forms 控制?具体静态定义的事件处理程序?

    3 回复  |  直到 15 年前
        1
  •  4
  •   Community Mohan Dere    8 年前
        3
  •  0
  •   Peter    9 年前

    Private Function getEventHandlers(ctrl As Control) As System.ComponentModel.EventHandlerList
        Dim value As System.ComponentModel.EventHandlerList = Nothing
        Try
            Dim propInfo As System.Reflection.PropertyInfo = GetType(Control).GetProperty("Events", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Static)
            If propInfo IsNot Nothing Then value = CType(propInfo.GetValue(ctrl), System.ComponentModel.EventHandlerList)
        Catch ex As Exception
        End Try
        Return value
    End Function
    

    Private Function hasEventHandler(ctrl As Control, Optional eventName As String = "Click") As Boolean
        Dim value As Boolean = False
        Try
            Dim handlerList As System.ComponentModel.EventHandlerList = getEventHandlers(ctrl)
            Dim controlEventInfo As System.Reflection.FieldInfo = GetType(Control).GetField("Event" + eventName, Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Static)
            If controlEventInfo IsNot Nothing Then
                Dim eventKey As Object = controlEventInfo.GetValue(ctrl)
                Dim EventHandlerDelegate As [Delegate] = handlerList.Item(eventKey)
                If EventHandlerDelegate IsNot Nothing Then value = True
            End If
        Catch ex As Exception
        End Try
        Return value
    End Function