Recording and replaying raised events in VB.NET

I have implemented communication between the two classes using events in VB.NET. Now I want to store (record) all the events that happened and re-raise them (replay) later.

Here's what I already have:

Class1:

Public Event Button1Pressed(ByVal sender As Object)

Private Sub btnButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnButton.Click
    RaiseEvent Button1Pressed(Me)
End Sub

Public Sub handleDisplayChanged(ByVal sender As System.Object, ByVal txt As String)

        '... Some code
End Sub

      

Class 2:

Public Event DisplayTextChangedEvent(ByVal sender As System.Object, ByVal text As String)

'In the constructor:
AddHandler Me.DisplayTextChangedEvent, AddressOf class1Instance.displayText
AddHandler class1Instance.Button1Pressed, AddressOf Me.buttonPressed

'Somewhere in the logic:
Public Sub buttonPressed(ByVal sender As Object)

    'Compute text
    '...
    RaiseEvent DisplayTextChangedEvent(text)
End Sub

      

I could add another event handler that I want to record, but then in the handler I only get the parameters that are passed to the event, not the event itself. Another thing is that I don't know how to solve that I cannot raise the event from the outer class.

Is there a good solution for my problem?

+3


source to share


1 answer


To record an event, you can make a helper method that records and raises. So instead of this:

RaiseEvent Button1Pressed(Me)

      

do the following:

Sub RaiseButton1PressedEvent()
  RaiseEvent Button1Pressed(Me)  <--raise the event

  RecordEvent("Button1Pressed")  <--record the event
End Sub

      

Of course it RecordEvent

must be designed.



To raise an event from an outer class, execute this method:

Sub ReplayButton1PressedEvent()
  RaiseEvent Button1Pressed(Me)  <--raise the event
End Sub

      

Now, if you have a lot of events, it can get tiresome. There are some good ways to solve this problem:

  • There is probably a way to raise the event using reflection based on the event name so that you can implement one generic function instead of one for each event, namely instead Sub RaiseButton1PressedEvent()

    , you could haveSub RaiseEventByName(sEventName As String)

  • Use code generation to allocate a partial class with Raise and Replay methods for each of the events you want to track.

0


source







All Articles