sabato 24 dicembre 2011

Handling events in VB6 exposed on a C# class library through COM

In order to create a .NET class library that can be called by a VB6 client make ComVisible the class and add the interop tags as in the following code

namespace MyClassLibraryNamespace
{

    // The delegate type for our custom event.
    [ComVisible(false)]
    public delegate void MyEventHandler(object sender, EventArgs e);

    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    [ComVisible(true)]
    public interface IMyEvents
    {
        [DispId(1)]//Each event must have a unique DispId
        void OnMyEvent(object sender, EventArgs e);
    }


    [ClassInterface(ClassInterfaceType.None)]
    [ComSourceInterfaces(typeof(IMyEvents))]
    [ComVisible(true)]
    public class MyControl
    {
        public event MyEventHandler OnMyEvent;
  
    }
}

Compile the class library with "Register for COM interop" option in the Build tab of Visual Studio 2010: it will generate a tlb file aside the dll.

Add a reference to the tlb file in the VB6 project

Private WithEvents myCtrl As MyControl

Private Sub Form_Load()
 Set myCtrl = New MyControl
End Sub


Private Sub myCtrl_OnMyEvent(ByVal sender As Variant, ByVal e As EventArgs)
 MsgBox "MyEvent"
End Sub