VB6 中如何訪問C# Dll 中的方法、屬性以及事件

來源:互聯網
上載者:User

一個簡單的例子實現VB6中訪問C# dll中的方法、屬性以及事件。

C# DLL

1) 要使得C# dll中的方法、屬性以及事件在VB6中暴露出來,以便寫代碼方便,需要加入相應的介面

- 方法和屬性的介面,本例中為IComInterOpClass

[Guid("12A7D9AE-B42F-4a91-9EEE-5E0951A552E2")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IComInterOpClass
{
//Method
string SayHello();
//Property
string Name { get; set; }
}

- 事件的介面,本例中為IComInterOpEvent

[Guid("868FD423-2504-4f5c-AB47-9F2B7DB8ED2C")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
public interface IComInterOpEvent
{
void EventTest(string msg);
}

 

2) 實現部分,注意事件的介面不需要繼承,它是以Attribute的方式加入的。本例中的事件是用timer實現5秒鐘觸發一次。

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) 至此,C# dll部分就完成了,最後記得將項目的Register for COM InterOp選上。

 

VB部分

 

1) 首先聲明兩個變數,一個是類的,一個是事件的。

 

Public obj As ComInterOpLibrary.ComInterOpClass
Public WithEvents objEvent As ComInterOpLibrary.ComInterOpClass

 

 

2) 然後進行初始化,本例是放在Form Load的時候進行的。

Private Sub Form_Load()

Set obj = New ComInterOpLibrary.ComInterOpClass
Set objEvent = obj

End Sub

 

 

3) 調用屬性和方法

Dim ret As String

'Call property
obj.Name = txtName.Text

'Call Method
ret = obj.SayHello()

lblShow.Caption = ret

 

 

4) 訪問事件

Private Sub objEvent_EventTest(ByVal msg As String)

'Call event
List1.AddItem msg

End Sub

 

5) 運行介面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.