VB6 窗体如何处理来自 C# .NET DLL 的事件



在工作中,我们有一个旧的VB6应用程序,我需要教新的(呃(技巧。我要做的第一件事是让它从用 C# 编写的 .Net COM 可见 DLL 调用方法。我有那个工作。现在,我需要让它处理来自同一 DLL 的传入进度通知事件。下面是 C# 代码:

namespace NewTricksDLL
{
[ComVisible(true)]
[ComSourceInterfaces(typeof(IManagedEventsToCOM))]
public class NewTricks
{
public delegate void NotificationEventHandler(string Message);
public event NotificationEventHandler NotifyEvent = null;
public string SomeMethod(string message)
{
return Notify(message);
}
private string Notify(string message)
{
if (NotifyEvent != null)
NotifyEvent("Notification Event Raised.");
return message;
}
}
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
interface IManagedEventsToCOM
{
[DispId(1)]
void NotifyEvent(string Message);
}
}

这是我尝试以 VB6 形式使用它的方式

Option Explicit
Public WithEvents newTricks as NewTricksDLL.NewTricks
Private Sub Command1_Click()
Dim response as String
Set newTricks = New NewTricksDLL.NewTricks
AddHandler newTricks.NotifyEvent, AddressOf NotifyEventHandler
response = newTricks.SomeMethod("Please send an event...")
End Sub
Private Sub NotifyEventHandler()
'Nothing
End Sub

我的问题是,当我尝试运行VB6表单时,我得到Compile error: Object does not source automation events.

如果我删除WithEventsCommand1_ClickSub 确实会运行并且response确实包含"Please send an event..."因此我知道该方法是通过 COM 调用的。

我在实施事件时哪里出了问题?

您将对象声明为 WithEvents,因此该对象应显示在 Visual Studio (VB6 IDE( 代码窗口的左侧下拉列表中。选择对象后,newTricks在您的案例中,右侧下拉列表将显示可用事件。单击所需的事件,IDE 将为您生成事件处理程序,但您也可以手动键入以下内容:

Private Sub newTricks_NotifyEvent()
' handle your event here
End Sub

问题在于缺乏对类和接口的适当装饰。 此 C# 代码允许 VB6 IDE 查看可用事件并为事件生成处理程序模板,但尝试在 VB6 中实例化类会导致Object or class does not support the set of events。 我为这个问题提出了一个新问题。

{
[ComVisible(true)]
[Guid("16fb3de9-3ffd-4efa-ab9b-0f4117259c75")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ITransfer
{
string SendAnEvent();
}
[ComVisible(true)]
[Guid("16fb3de9-3ffd-4efa-ab9b-0f4117259c74")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IManagedEventsToCOM
{
[DispId(1)]
void NotificationEvent();
}
[ComVisible(true)]
[Guid("dcf177ab-24a7-4145-b7cf-fa06e892ef21")]
[ComSourceInterfaces(typeof(IManagedEventsToCOM))]
[ProgId("ADUTransferCS.NewTricks")]
public class NewTricks : ITransfer
{
public delegate void NotificationEventHandler();
public event NotificationEventHandler NotifificationEvent;
public string SendAnEvent()
{
if (NotifificationEvent != null)
NotifificationEvent();           
}
}
}

最新更新