In this tutorial, we’ll delve into the fascinating world of COM Interoperability, demonstrating seamless communication between Visual Basic 6 (VB6) and C# applications. Throughout the tutorial, you’ll learn the crucial steps to establish this communication channel, unlocking the potential for VB6 and C# applications to work in harmony. You’ll witness the power of COM Interoperability as the C# library displays the received message in a message box, showcasing a practical integration between legacy and modern programming environments.
Check the repository for the full source code
https://github.com/nikosportolos/COM-Interoperability-in-.NET/tree/main/part-ii
Right-Click on Project
Properties (Alt+Enter)
- Application tab
- Assembly Information button
- Check option “Make assembly COM Visible”
- Create your Event interface
[Guid("123456789-1234-1234-1234-123456789123")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IVB6InteropEvents
{
[DispId(1)]
void SampleEvent(string Message);
}
Implement Events
Create delegate
public delegate void SampleEventHandler(string Message);
Create event
public new event SampleEventHandler SampleEvent = null;
Create event trigger
public void FireSampleEvent(string Message); [Guid("7E6D6368-0033-49F6-9FE3-B2D409572869")] [ProgId("VB6Interop")] [ClassInterface(ClassInterfaceType.None)] [ComSourceInterfaces(typeof(IVB6InteropEvents))] [ComVisible(true)] public class VB6Interop : IVB6Interop { public void SampleMethod(string Message) { try { //MessageBox.Show(Message); FireSampleEvent("I received the message: " + Message); } catch (Exception ex) { throw new Exception("Exception occured in SampleMethod(): ", ex); } } // Create delegate [ComVisible(true)] public delegate void SampleEventHandler(string Message); // Create event public new event SampleEventHandler SampleEvent = null; // Create event trigger public void FireSampleEvent(string Message) { try { if (SampleEvent != null) SampleEvent(Message); } catch (Exception ex) { throw new Exception("Exception occured in FireSampleEvent(): ", ex); } } }
- Create a new VB6 Project
- Select Standard EXE
Option Explicit
' Declare a VB6Interop object
Public WithEvents VB6 As VB6Interop.VB6Interop
Private Sub Command1_Click()
' Use SampleMethod() of VB6Interop
VB6.SampleMethod "Hello VB6!"
End Sub
Private Sub Form_Load()
' Initialize VB6Interop object
Set VB6 = New VB6Interop.VB6Interop
End Sub
' Implement SampleEvent
Private Sub VB6_SampleEvent(ByVal Message As String)
MsgBox Message
End Sub