在工作中,我们有一个旧的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.
如果删除WithEvents
,则Command1_Click
子程序会运行,并且response
确实包含"Please send an event..."
,所以我知道该方法是通过COM调用的。
该活动的执行方式哪里出问题了?
您已将该对象声明为WithEvents,因此该对象应显示在Visual Studio(VB6 IDE)的代码窗口的左侧下拉列表中。选择对象(在您的情况下为newTricks
)后,右侧的下拉列表将显示可用事件。单击所需的事件,IDE将为您生成事件处理程序,但是您也可以手动键入该事件处理程序:
Private Sub newTricks_NotifyEvent()
' handle your event here
End Sub