1

I have the following code that creates a button :

    Dim B As New Button
    B.Parent = Me
    B.Location = New Point(50, 50)

    AddHandler B.Click, Sub()
                            MsgBox("Hi")
                        End Sub

    'I try to get the field info for the click event inorder to get the event handler and remove it
    Dim FieldInfo As FieldInfo = B.GetType.GetField("Click", BindingFlags.[Static] Or BindingFlags.NonPublic Or BindingFlags.Public)

    Dim obj As Object = FieldInfo.GetValue(Obj_)
    Dim EI As EventInfo = Obj_.GetType.GetEvent(EventName)
    EI.RemoveEventHandler(Obj_, obj)

but the FieldInfo is constantly null. I tried with many event names ClickEvent, EventClick... but none of them allowed me to get a result.

Does anyone know what is missing to my code please ?

Thank you in advance.

Thomas Carlton
  • 5,344
  • 10
  • 63
  • 126

2 Answers2

1

I suggest you to go through this - How to: Hook Up a Delegate Using Reflection

Get an EventInfo object representing the event, and use the EventHandlerType property to get the type of delegate used to handle the event. In the following code, an EventInfo for the Click event is obtained.

Code snippet:

   Dim evClick As EventInfo = tExForm.GetEvent("Click")
    Dim tDelegate As Type = evClick.EventHandlerType

You can easily get their list (type.GetEvents()), add another handler (EventInfo.AddEventHandler()) or remove a handler (EventInfo.RemoveEventHandler()). To get a list of attached delegates you have to do something more.

References:
Removing Event Handlers using Reflection
How to get event handlers list using reflection
Raise an event via reflection in c#
Getting event via reflection

Community
  • 1
  • 1
Niranjan Singh
  • 18,017
  • 2
  • 42
  • 75
0

You need to use GetEvent() not GetField().

See http://msdn.microsoft.com/en-us/library/50943xt0(v=vs.110).aspx

ie

Dim myEventInfo As EventInfo = B.GetType.GetEvent("Click", BindingFlags.[Static] Or BindingFlags.NonPublic Or BindingFlags.Public)

You can also use the general GetMember method, which returns a (array of)MethodInfo which is a superclass of (FieldInfo, EventInfo) etc, it returns an array as there could be several matches (ie overloaded methods etc).

Niranjan Singh
  • 18,017
  • 2
  • 42
  • 75
tolanj
  • 3,651
  • 16
  • 30
  • Thank you for your answer. Actually i'm trying to remove an event handler dynamically. Do you know if this is possible without using GetField ? (I updated the post) – Thomas Carlton Oct 27 '14 at 11:11
  • This was a full answer to your original question. Your second question should really be, well, a second question! Anyway @Niranjan Kala 's answer seems to cover all the rest of the info you have asked for, http://dkowalski.com/blog/archive/2009/12/22/how-to-get-event-handlers-list-using-reflection.aspx specifically. Please accept either answer. – tolanj Oct 27 '14 at 12:20