对于自定义事件,我可以像这样检查处理程序:
If Object.EventNameEvent Is Nothing Then
MsgBox("Is not handling it.")
End If
...但是我该如何做同样的事情,例如,检查在设计器中生成的按钮的“.click”事件?这不起作用:
If Button1.ClickEvent Is Nothing Then
MsgBox("Is not handling it.")
End If
更新
我的要求示例:
MsgBox(HasAttachedHandler(MySub, Button1.Click)) ' Expected result: True
MsgBox(HasAttachedHandler(MyFunc, Button1.Click)) ' Expected result: False
Private Sub MySub() Handles Button1.Click, Button2.Click
' bla bla bla
End Sub
Private Function MyFunc() Handles Button2.Click
' bla bla bla
End Function
更新 2:
我正在尝试使用@varocarbas解决方案,但并没有完全满足我的需要,因此我尝试进行必要的修改以使其正常工作。问题是事件“FontChaged”没有返回所需的结果,如您在此处看到的:
Public Class Form1
Private WithEvents Button1 As New Button
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
' This is working (Result True):
MsgBox(HasAttachedHandler(Button1, "Click", "Button1_Click")) ' Result: True
' This is not working (Result False):
MsgBox(HasAttachedHandler(Button1, "FontChanged", "Button1_Click")) ' Expected result: True
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles _
Button1.Click, _
Button1.MouseHover, _
Button1.GotFocus, _
Button1.Enter, _
Button1.FontChanged, _
Button1.AutoSizeChanged
End Sub
Private Function HasAttachedHandler(ByVal ctl As Control, ByVal eventname As String, ByVal targetMethod As String) As Boolean
For Each evnt In ctl.GetType().GetEvents()
' Get secret key for the current event:
Dim curEvent As Reflection.FieldInfo = GetType(Control).GetField("Event" & evnt.Name, Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Static)
If (curEvent IsNot Nothing) Then
Dim secret As Object = curEvent.GetValue(Nothing)
' Retrieve the current event:
Dim eventsProp As Reflection.PropertyInfo = GetType(System.ComponentModel.Component).GetProperty("Events", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)
Dim events As System.ComponentModel.EventHandlerList = DirectCast(eventsProp.GetValue(ctl, Nothing), System.ComponentModel.EventHandlerList)
If (Not IsNothing(events(secret))) AndAlso curEvent.Name.ToLower = "event" & eventname.ToLower Then
Dim handler As [Delegate] = events(secret)
Dim method As Reflection.MethodInfo = handler.Method
If (targetMethod = method.Name) Then Return True
End If
End If
Next
Return False
End Function
End Class