tags:

views:

54

answers:

2

In a Visual Basic .NET application, is there a way to use Handles on an object referenced in a DLL written in C#? Compiling the code gives me the error:

'Handles' in modules must specify a 'WithEvents' variable qualified with a single identifier.

I'm writing the Visual Basic .NET application, but I do have the source code of the C# library available.

My current code looks something like this:

WithEvents Friend Module As ModuleNamespace.Module
Sub EventHandler() Handles Module.Events.Event1
    Console.WriteLine("Event1 fired.")
End Sub

Replacing Module, ModuleNamespace, and Event1 with the actual names.

A: 

It sounds like you don't have an object instance handy for the events to be bound to. Can you try using AddHandler instead of the Handles keyword?

For example:

Private Sub BindEvents(ByVal someObject AS ClassInLibrary)

  AddHandler someObject.EventName, AddressOf Foo

End Sub

Private Sub Foo(ByVal sender As Object, ByVal e As EventArgs)

End Sub
Andrew Kennan
I'm using AddHandler now, but I was just wondering if there was a more efficient/cleaner way to accomplish the same goal, as runtime binding isn't necessary for my application.
Hello71
Unless you've got a module level variable like MarkJ suggests you'll have to call AddHandler yourself. When you use WithEvents and Handles the compiler actually emits a property and calls AddHandler itself in the setter.
Andrew Kennan
+2  A: 

You need a module level variable to contain the object instance. Air code:

 Private WithEvents mMyObject As CSharpObject

 Private Sub MyEvent(...) Handles mMyObject.SomeEvent 
MarkJ