1. VB6 call C# by interop
Continue from the last blog. The five things we need to achieve are:
Due to the technical requirement and the business needs, we have decided to implement the following:
1. Created an interop to facilitate communicate between VB6 and Bumble Bee
2. Use WinMsg to communicate between interop and Winform for .net2.0 – this is to ensure that if Bumble Bee exists on the same machien as the VB6 program, the two programs will be the minimum lag.
3. Interop call C# WinForm by TCP Server – if the Bumble Bee program does not co-locate on the VB6 program’s machine, we need to use TCP Server/Listener technology to do it.
4. Winform dynamically load WPF – most of the funcationlity will be implemented on the Winform which runs on the required .net2.0. For the 3.5 funcationlity that requires WPF, we will simply call WPF through Winform when we can dynamically determine if .net 3.5 exists or not on the particular machine.
5. To ensure step 4, we have to make sure tha the project can install dynamically on 2.0 or 3.5.
Today, let’s talk about 1:
As you know, we can expose the .NET Framework components to COM. Then the VB6 code could consume it as usual.
Perform the following steps:
Create a .Net class libray project just like normally.
Open the properties of the project and click the Build tab. Make sure the Register For COM Interop option selected.
Create a .Net Class:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace InteropLib
{
public interface IInterop
{
string[] GenInfo { get; set; }
int Flag { get; set; }
void notifyCSharpForm();
}
[GuidAttribute("D5E4C17E-3C1C-4519-AC39-F7749CE81AAB")]
public class Interop : IInterop
{
private string[] _GenInfo = null;
private int _flag = 0;
public string[] GenInfo
{
get
{ return _GenInfo;}
set
{_GenInfo = value;}
}
public int Flag
{
get
{return _flag;}
set
{_flag = value;}
}
public void notifyCSharpForm()
{
//Notify the WinForm to get the GenInfo and Flag
.....
}
}
}
If you compile the application with the code just shown and there are no errors, the assembly will be visible to COM.
Consume it in VB6
Dim ocdInterop As InteropLib.Interop
Private Sub cmdFinish_Click()
Set interop = New InteropLib.Interop
interop .Flag = -1
Some Tips:
Tip 1. After compiling your assembly to a DLL, you can register it for COM Interop from the command line:
regasm c:\path\MyDll.dll /tlb:MyDll.tlb
Tip 2. Add GuidAtrribute for the assembly, then it will keep a unique reference for VB6.
If the application is recompiled, no need to recomiple the VB6 code again. Because the GUIDs is always same for VB6.
[GuidAttribute("D5E4C17E-3C1C-4519-AC39-F7749CE81AAB")]