A simple example is used to access methods, attributes, and events in C # DLL in VB6.
C # DLL
1) to expose methods, attributes, and events in C # DLL to VB6 for easy code writing, you need to add corresponding interfaces.
-Method and attribute interfaces. In this example, icominteropclass is used.
[Guid("12A7D9AE-B42F-4a91-9EEE-5E0951A552E2")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IComInterOpClass
{
//Method
string SayHello();
//Property
string Name { get; set; }
}
-Event interface. In this example, It is icominteropevent.
[Guid("868FD423-2504-4f5c-AB47-9F2B7DB8ED2C")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
public interface IComInterOpEvent
{
void EventTest(string msg);
}
2) implementation part. Note that the event interface does not need to be inherited. It is added as an attribute. In this example, the event is triggered once every 5 seconds using timer.
namespace ComInterOpLibrary
{
public delegate void EventTestHandler(string message);
[Guid("BA6DF62E-D59E-4e46-B2E6-F1CD990A1E18")]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfacesAttribute("ComInterOpLibrary.IComInterOpEvent")]
[ProgId("ComInterOpClass")]
public class ComInterOpClass : IComInterOpClass
{
private Timer myTimer = null;
//Event
public event EventTestHandler EventTest;
//Property
public string Name { get; set; }
public ComInterOpClass()
{
myTimer = new Timer(5000);
myTimer.AutoReset = true;
myTimer.Enabled = true;
myTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);
}
void myTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if (EventTest != null)
{
EventTest("Good day!");
}
}
#region IComInterOpClass Members
//Method
public string SayHello()
{
return "Hello " + Name;
}
#endregion
}
}
3) at this point, the C # DLL part is complete. Finally, select the project's register for com InterOP.
VB Section
1) declare two variables, one of which is class and the other is event.
Public obj As ComInterOpLibrary.ComInterOpClass
Public WithEvents objEvent As ComInterOpLibrary.ComInterOpClass
2) perform initialization. In this example, it is implemented during form load.
Private Sub Form_Load()
Set obj = New ComInterOpLibrary.ComInterOpClass
Set objEvent = obj
End Sub
3) Call attributes and Methods
Dim ret As String
'Call property
obj.Name = txtName.Text
'Call Method
ret = obj.SayHello()
lblShow.Caption = ret
4) Access Events
Private Sub objEvent_EventTest(ByVal msg As String)
'Call event
List1.AddItem msg
End Sub
5) running interface