Reputation: 143
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.
Upvotes: 5
Views: 433
Reputation: 24253
Another option allowing you to have more control is a callback interface.
You expose an interface in your .NET library that has a single EventXYZ
method.
Your VB6 class (and other listeners) can implement this interface and pass a reference to the object to your .NET class for it to raise the method on.
This is essentially the same method that COM and .NET events use internall, but .NET has more granularity down to the event level.
Upvotes: 2
Reputation: 24253
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
Upvotes: 2