Search code examples
c#vb6com-interop

Programmatically unsubscribe from event


I have a vb6 app which is using a COM object (COM exposed C# object). The vb6 app is subscribing to an event published by the COM (C#) object.

My problem is that I don't know how to programmatically unsubscribe from that event. The only way that I know how to unsuscribe is by not subscribing in the first place (i.e. commenting out the event handler in the vb6 code).

Is there a way to do that unsubscribing at runtime (programmatically)? Maybe by doing something on the C# side by identifying the delegate that corresponds to the vb6 event handler and not calling it?

Thanks in advance.


Solution

  • You can stop receiving events in VB6 by keeping two object reference variables, one with the WithEvents keyword and one without. When you want to subscribe, set the first to the same object as the second, and to unsubscribe, set the first to Nothing. You need to make sure you release/replace both of them when you want to release the object.

    Dim MyObject As MyClass
    Dim WithEvents MyObjectEvents As MyClass
    
    Public Sub MyObjectEvents_EventName()
      MsgBox "Received event"
    End Sub
    
    Private Sub Subscribe()
      Set MyObjectEvents = MyObject
    End Sub
    
    Private Sub Unsubscribe()
      Set MyObjectEvents = Nothing
    End Sub