COM Interoperability – Part I

COM Interoperability

Basic communication between Visual Basic and C#

This tutorial provides a quick and easy guide for basic communication between Visual Basic and C# utilizing the COM Interoperability in .NET.

We’ll focus on building a C# class library designed to receive messages from a VB6 application. The VB6 component features a straightforward form housing a button that dispatches a message to the C# library.

Check the repository for the full source code

https://github.com/nikosportolos/COM-Interoperability-in-.NET/tree/main/part-i

Table of Contents


.NET class library

Setup .NET project

  1. Create a new C# Project in Visual Studio

    dotnet_01
  2. Select Class Library

    dotnet_02
  3. Make assembly COM Visible

  • Right-Click on Project

  • Properties (Alt+Enter)

    dotnet_03
    • Application tab
    • Assembly Information button
    dotnet_04
    • Check option “Make assembly COM Visible”
    dotnet_05
  1. Register for COM Interop

    • Build tab
    • Output section
    • Check option “Register for COM interop”
    dotnet_06

C# source code

  1. Access InteropServices Namespace
using System.Runtime.InteropServices
  1. Create your Class interface
[Guid("123456789-1234-1234-1234-123456789123")]
[ComVisible(true)]
public interface IVB6Interop
{
    [DispId(1)]
    void SampleMethod(string Message);
}
  1. Implement the IVB6Interop interface
[Guid("123456789-1234-1234-1234-123456789123")]
[ProgId("VB6Interop")]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IVB6InteropEvents))]
[ComVisible(true)]
public class VB6Interop : IVB6Interop
{
    public void SampleMethod(string Message)
    {
        try
        {
            MessageBox.Show(Message);
        }
        catch (Exception ex)
        {
            throw new Exception("Exception occured in SampleMethod(): ", ex);
        }
    }
}

VB6 winform app

Setup VB6 project

  1. Create a new VB6 Project
  • Select Standard EXE
vb_01
  • Add VB6Interop.dll reference
    • Project

    • References

      vb_02
    • Check VB6Interop Reference

      vb_03

VB6 source code

  1. Declare a VB6Interop object
Public VB6 As VB6Interop.VB6Interop
  1. Initialize VB6Interop object
Private Sub Form_Load()
    Set VB6 = New VB6Interop.VB6Interop
End Sub
  1. Use SampleMethod() of VB6Interop on button click
Private Sub Command1_Click()
    VB6.SampleMethod "Hello VB6!"
End Sub

…and we’re done!

Demo

vb_04

You may also be interested in