Tracing all events in VB.NET

前端 未结 1 1484
小蘑菇
小蘑菇 2020-12-22 01:55

I keep running into situations where I don\'t know what event I have to listen to in order to execute my code at the correct time. Is there any way to get a log of all event

相关标签:
1条回答
  • 2020-12-22 02:24

    The only way that I can think of is to use Reflection to enumerate all of the events and wire up a generic handler which would be a PITA.

    Is the problem with Framework events? If so, Microsoft does a pretty good job of giving event life-cycle/call order.

    Edit

    So here's a global event capture routine:

    Private Sub WireAllEvents(ByVal obj As Object)
        'Grab all of the events for the supplied object
        Dim Events = obj.GetType().GetEvents()
        'This points to the method that we want to invoke each time
        Dim HandlerMethod = Me.GetType().GetMethod("GlobalHandler")
        'Loop through all of the events
        For Each ev In Events
            'Wire in a handler for the event
            ev.AddEventHandler(obj, [Delegate].CreateDelegate(ev.EventHandlerType, Me, HandlerMethod))
        Next
    End Sub
    Public Sub GlobalHandler(ByVal sender As Object, ByVal e As EventArgs)
        'Probably want to do something more meaningful here than just tracing
        Trace.WriteLine(e)
    End Sub
    

    To wire it in just call WireAllEvents(Me.DataGridView1) supplying your object. Almost all MS events use sender/e (including DataGridView) format but if for some reason it doesn't I think this code will error out. But I just tested it with both a DataGridView and Form and it worked as expected.

    0 讨论(0)
提交回复
热议问题