【问题标题】:Make COM Interop Events visible from Interface使 COM 互操作事件从接口可见
【发布时间】:2019-12-20 16:31:12
【问题描述】:

我的代码如下例所示:

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 界面看不到事件。

有没有办法做到这一点?

【问题讨论】:

  • 不,在类型库中,源(或事件)接口是为 coclass 声明的。
  • 很好的例子,它极大地帮助了我将 VB6 用户控件迁移到托管代码。

标签: c# events com interop


【解决方案1】:

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

这是我喜欢思考的方式:

接口是两个对象同意使用的东西,因此“客户端”可以向“服务器”发送命令(“服务器,做 XYZ!”)。事件只是两个对象也同意使用的不同接口,但相反:即“服务器”对象向“客户端”发送命令。

是否支持给定的事件接口是对象的属性,而不是对象可能支持的任何接口的属性。服务器对象说:“给我一个ButtonEvents 接口指针,我会用它告诉你什么时候点击了按钮”。提供该优惠的不是IButton 界面。

这也是为什么你必须将[ComSourceInterfaces] 属性应用到类Button,而不是应用到接口IButtonButton CoClass 是提供报价的人。

让事件看起来特别或怪异的是,我们需要使用一种有点复杂和令人困惑的舞蹈(“连接点”)来传递事件的接口指针。 WithEvents 是让 VB6 为你“跳舞”的方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 2011-05-25
    • 2013-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多