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
Right-Click on Project
Properties (Alt+Enter)
- Application tab
- Assembly Information button
- Check option “Make assembly COM Visible”
- Access InteropServices Namespace
using System.Runtime.InteropServices
- Create your Class interface
[Guid("123456789-1234-1234-1234-123456789123")]
[ComVisible(true)]
public interface IVB6Interop
{
[DispId(1)]
void SampleMethod(string Message);
}
- 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);
}
}
}
- Create a new VB6 Project
- Select Standard EXE
- Declare a VB6Interop object
Public VB6 As VB6Interop.VB6Interop
- Initialize VB6Interop object
Private Sub Form_Load()
Set VB6 = New VB6Interop.VB6Interop
End Sub
- Use SampleMethod() of VB6Interop on button click
Private Sub Command1_Click()
VB6.SampleMethod "Hello VB6!"
End Sub
…and we’re done!