VB.Net如何引发COM事件

时间:2014-07-07 12:33:46

标签: .net vb.net events com-interop autoit

我正在尝试通过COM集成Autoit和VB.NET。我有如何使函数成为COM可见的属性,但如何使事件对COM可见

<ComClass(Core.ClassId, Core.InterfaceId, Core.EventsId)>
Public Class Core
    Public Const ClassId As String = "790D4506-D57D-4E2D-935A-1CC02C4B7CB4"
    Public Const InterfaceId As String = "0568FCF5-248C-4853-AFC6-309A838EA978"
    Public Const EventsId As String = "E81585D3-D5C3-4344-A830-D18A54F6A64E"
    Public Event AnEvent As EventHandler
    Public Sub New()
        MyBase.New()
    End Sub
    Public Sub newevent(yourstring As String)
        Dim e As DefaultEventArgs = New DefaultEventArgs(yourstring)
        RaiseEvent AnEvent(Me, e)
    End Sub
End Class

Public Class DefaultEventArgs
    Inherits EventArgs
    Dim str As String
    Public Sub New(astr As String)
        Me.str = astr
    End Sub
End Class

和自动代码

Func MyHandler($test)
    MsgBox(0,"","It's Finally Working")
EndFunc
DllOpen("Au3Magic.dll")
$test = ObjCreate("Au3Magic.Core")
if IsObj($test) then
    MsgBox(0,'',"No COM Failure")
    ObjEvent("Au3Magic.AnEvent","MyHandler")
    $test.newevent("test")
Else
    MsgBox(0,'',"Complete COM Failure")
EndIf

1 个答案:

答案 0 :(得分:1)

您需要将类拆分出来,以便为事件和方法使用单独的接口,然后创建一个委托并让您的事件调用它。

这是一个COM Interop类的框架,它引发了一个名为UpdateProgress

的事件
Imports System.Runtime.InteropServices

<ComVisible(True)> _
<Guid("zzzzzzzzzzzzzzzzzzzzzz"), _
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)> _
Public Interface IEventSkeletonEvents
    <System.Runtime.InteropServices.DispId(1)> Sub UpdateProgress(ByVal progressPercentage As Int32)
End Interface

<ComVisible(True)> _
<Guid("yyyyyyyyyyyyyyyyyyyy"), _
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)> _
Public Interface IEventSkeleton
    <System.Runtime.InteropServices.DispId(1)> Function Suspend() As Boolean
End Interface

<ComVisible(True)> _
<Guid("xxxxxxxxxxxxxxxxxxxx")> _
<ComDefaultInterface(GetType(IEventSkeleton))> _
<ComSourceInterfaces(GetType(IEventSkeletonEvents))> _
Public Class EventSkeleton : Implements IEventSkeleton

    <System.Runtime.InteropServices.ComVisible(False)> _
    Public Delegate Sub UpdateProgressDelegate(ByVal progressPercentage As Int32)
    Public Event UpdateProgress As UpdateProgressDelegate

    Public Function Suspend() As Boolean Implements IEventSkeleton.Suspend
        For i As Integer = 1 To 10
            System.Threading.Thread.Sleep(1000)
            RaiseEvent UpdateProgress(i * 10)
        Next
        Return True
    End Function
End Class