从界面可以看到COM互操作事件

时间:2015-05-27 08:26:17

标签: c# events com interop

我编写的代码如下例所示:

public delegate void ClickDelegate(int x, int y);
public delegate void PulseDelegate();

[Guid("39D5B254-64DB-4130-9601-996D0B20D3E5"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
[ComVisible(true)]
public Interface IButton
{
  void Work();
}

// 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 ButtonEvents
{
    void Click(int x, int y);
    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(ButtonEvents))]
public class Button : IButton
{
    public event ClickDelegate Click;
    public event PulseDelegate Pulse;

    public Button() { }

    public void CauseClickEvent(int x, int y) { Click(x, y); }
    public void CausePulse() { Pulse(); }

    public void Work() { /* Do some stuff */ }
}

这适用于VB。当我定义它时:

Dim WithEvents obj As Button

但我想用接口来定义它:

Dim WithEvents obj As IButton

这不起作用,因为从IButton界面看不到事件 有办法吗?

1 个答案:

答案 0 :(得分:1)

连接到对象事件的变量必须声明为对象的类型(CoClass)(在您的示例中为IButton)。界面(示例中为ButtonEvents)对事件一无所知,也不能用于请求它们。

这是我喜欢考虑的方式:

  

接口是两个对象同意使用的东西,因此"客户端"可以发送命令到服务器" ("服务器,执行XYZ!" )。事件只是两个对象同意使用的不同接口,但用于相反的:即,对于"服务器"对象将命令发送到"客户端"。

是否支持给定的Event接口是对象的属性,而不是对象可能支持的任何接口的属性。服务器对象说:"给我一个IButton界面指针,我会用它来告诉你何时点击按钮" 。它不是提供此优惠的[ComSourceInterfaces]界面。

这也是您必须将Button属性应用于类IButton而不是接口Button的原因。 WithEvents CoClass是提出要约的人。

使事件看起来特别或奇怪的是我们需要使用一种有点复杂和混乱的舞蹈("连接点")来传递事件的界面指针。 All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.是要求VB6进行舞蹈的方式。对你而言。

相关问题