For custom events I can check the handler like this:
If Object.EventNameEvent Is Nothing Then
MsgBox("Is not handling it.")
End If
...But how I can do the same, for example, to check a ".click" event of a button which is generated in the designer? This does not work:
If Button1.ClickEvent Is Nothing Then
MsgBox("Is not handling it.")
End If
UPDATE
Example of my requeriments:
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
UPDATE 2:
I'm trying to use the @varocarbas solution, but is not doing exactly what I need, so I've tried to make the necessary modifications to get it work. The problem is the event "FontChaged" is not returning the desired result as you can see here:
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