【问题标题】:C# component events?C# 组件事件?
【发布时间】:2009-07-17 00:30:51
【问题描述】:

我正在尝试编写一个公开事件的 C# 组件。该组件将由非托管 C++ 应用程序导入。根据一些教程,我想出了这段代码(用于 C# 端):

namespace COMTest
{
[ComVisible(true),
Guid("02271CDF-BDB9-4cfe-B65B-2FA58FF1F64B"),
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ITestEvents
{
    void OnTest();
}

[ComVisible(true),
Guid("87BA4D3A-868E-4233-A324-30035154F8A4")]
public interface ITest
{
    void RaiseTest();
} // End of ITest

[ComVisible(true),
Guid("410CD174-8933-4f8c-A799-8EE82AF4A9F2"),
ClassInterface(ClassInterfaceType.None),
ComSourceInterfaces(typeof(ITestEvents))]
public class TestImplimentation : ITest
{
    public TestImplimentation()
    {
    }

    public void RaiseTest()
    {
        if (null != OnTest)
            OnTest();
    }

    public delegate void Test (); //No need to expose this delegate
    public event Test OnTest;
}
}

现在我的 c++ 代码有一个简单的:

#import "COMTest.tlb" named_guids raw_interfaces_only

这会生成一个 tlh 文件。此 tlh 文件包含除我的事件 (OnTest) 之外的所有内容。我做错了什么?

【问题讨论】:

    标签: c# c++ .net com unmanaged


    【解决方案1】:

    COM 事件接收器对于外行来说是相当邪恶的。

    步骤基本是

    • 创建传出(源)接口
    • 实施 IConnectionPointContainer 和 IConnectionPoint 接口,使用 这些传递一个客户端实现 源接口的

    消息是,在 interop 命名空间中有一些属性可以帮助您(大部分)自动执行此操作 (ComSourceInterfacesAttribute) 有一个很好的使用示例 here

    【讨论】:

    • 谢谢,但这正是我在我的示例中所做的,那不起作用。
    • 我有这个工作。我没有意识到 tlh 文件只会为我正在使用的类生成信息。一旦我让我的 c++ 类从 ITestEvents 类继承,一切都开始正常工作。感谢您提供信息。
    猜你喜欢
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-21
    • 2011-07-23
    相关资源
    最近更新 更多