我有一个c#COM服务器为事件处理定义了一些委托。 这是来自MSDN的示例代码:
using System;
using System.Runtime.InteropServices;
namespace Test_COMObject
{
public delegate void ClickDelegate(int x, int y);
public delegate void ResizeDelegate();
public delegate void PulseDelegate();
// Step 1: Defines an event sink interface (ButtonEvents) to be
// implemented by the COM sink.
[GuidAttribute("1A585C4D-3371-48dc-AF8A-AFFECC1B0967")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
public interface MyButtonEvents
{
void Click(int x, int y);
void Resize();
void Pulse();
}
// Step 2: Connects the event sink interface to a class
// by passing the namespace and event sink interface
// ("EventSource.ButtonEvents, EventSrc").
[ComSourceInterfaces(typeof(MyButtonEvents))]
public class MyButton
{
public event ClickDelegate Click;
public event ResizeDelegate Resize;
public event PulseDelegate Pulse;
public MyButton()
{
}
public void CauseClickEvent(int x, int y)
{
Click(x, y);
}
public void CauseResizeEvent()
{
Resize();
}
public void CausePulse()
{
Pulse();
}
}
}
但是msdn只提供了一个VB示例来实现COM客户端事件接收器,有人能给我一个示例如何使用非托管c ++这样做吗? 下面是实现COM事件接收器的vb示例
' COM client (event sink)
' This Visual Basic 6.0 client creates an instance of the Button class and
' implements the event sink interface. The WithEvents directive
' registers the sink interface pointer with the source.
Public WithEvents myButton As Button
Private Sub Class_Initialize()
Dim o As Object
Set o = New Button
Set myButton = o
End Sub
' Events and methods are matched by name and signature.
Private Sub myButton_Click(ByVal x As Long, ByVal y As Long)
MsgBox "Click event"
End Sub
Private Sub myButton_Resize()
MsgBox "Resize event"
End Sub
Private Sub myButton_Pulse()
End Sub
答案 0 :(得分:1)
语言运行时通常会隐藏从COM对象接收事件所涉及的大量管道。但是如果你在原始C ++中这样做,那么你需要通过查询IConnectionPointContainer的接口指针来开始。这使您可以枚举所有外出接口。然后,您可以获取特定接口的IConnectionPoint。然后,您可以调用其Advise()方法来设置获取回调的接收器接口。这会给你一个cookie,你需要存储它。以后当您想取消订阅Unadvise电话时。
在MSDN Library中对它进行了相当好的描述,启动reading here。