Raising events in a class library exposed to COM

前端 未结 1 1117
小蘑菇
小蘑菇 2021-01-16 06:16

I\'m trying to write a wrapper to a service, which will be used by an existing VB6 project. I\'ve got most of the basic framework working, except for one important aspect: I

相关标签:
1条回答
  • 2021-01-16 06:53

    Its too much to write in a comment, so I'll make it an answer....

    First, identify the .net class you want to expose to COM. I'll pick a class called CORE.

    Create an interface that describes the EVENTS that the CORE object will source (ie generate).

    <ComVisible(True)> _
    <Guid("some guid here...use guidgen, I'll call it GUID1")> _
    <InterfaceType(ComInterfaceType.InterfaceIsIDispatch)> _
    Public Interface ICoreEvents
        <System.Runtime.InteropServices.DispId(1)> _
        Sub FileLoaded(ByVal Message As String)
    End Interface
    

    Next, Create an interface for the COM exposed properties and methods of your class.

    <ComVisible(True)> _
    <Guid("another GUID, I'll call it guid2")> _
    <InterfaceType(ComInterfaceType.InterfaceIsDual)> _
    Public Interface ICore
        ReadOnly Property Property1() As Boolean
        ReadOnly Property AnotherProperty() As ISettings
        ReadOnly Property Name() As String
        ReadOnly Property Phone() As String
    End Interface
    

    Now, create your actual .net class

    <ComVisible(True)> _
    <ClassInterface(ClassInterfaceType.None)> _
    <ComDefaultInterface(GetType(ICore))> _
    <ComSourceInterfaces(GetType(ICoreEvents))> _
    <Guid("a third GUID, I'll call it GUID3")> _
    Public Class Core
        Implements ICore
    
        <System.Runtime.InteropServices.ComVisible(False)> _
        Public Delegate Sub OnFileLoaded(ByVal Message As String)
        Public Event FileLoaded As OnFileLoaded
    End Class
    

    Now, when you need to raise the FileLoaded event, just RAISEEVENT FILELOADED(Message) from within your class. .NET will forward the event out to COM because you've hooked up the COMSourceInterfaces attribute.

    The attribute is shorthand for much of of this, but unfortunately doesn't give you quite the control that you need to do certain things (for instance retain version compatibility on your com interfaces).

    0 讨论(0)
提交回复
热议问题