Reputation: 1193
Part of a Visual Basic program is being moved to .NET dll.
Parameter call can be passed successfully & everything run fine.
How can I pass a callback function of VB6 for .NET to call after a long running async task?
In .NET
Public Delegate Function VBCallBackFunc() As Integer
Public Function DoSomething(a As String, b As String, c As String, _
parent As IntPtr, Optional ByVal CallbackAddr As VBCallBackFunc = Nothing) As Boolean Implements _DotNetLib.DoSomething
VB6
result = DotNetLib.DoSomething(strA, strB, strC, Me.hwnd, AddressOf DotNetCallback)
Public Function DotNetCallback() As Long
MsgBox ("Callback")
End Function
In object browser of VB:
Function DoSomething(strA As String, strB As String, strC As String,
parent As Long, [CallbackAddr As VBCallBackFunc]) As Boolean
Member of DotNetLib
But it said "Invalid use of AddressOf operator" ???
Upvotes: 1
Views: 1428
Reputation: 10855
The comments related to using Events are a good option, but I tend to use interfaces more, so here is a solution for that.
(Free-hand code, you will need to syntax check and the names can be cleaned up, they are just for illustration purposes)
In .NET:
Create an COM exposed interface for your callback:
Public Interface IVBCallBack
Public Function VBCallBackFunc() As Integer
End Interface
Change your DoSomething be like this:
Public Function DoSomething(a As String, b As String, c As String, parent As IntPtr, ByVal CallbackAddr As IVBCallBack) As Boolean
In VB6:
result = DotNetLib.DoSomething(strA, strB, strC, Me.hwnd, Me)
(And you will need your class, control, or form to Implements IVBCallBack
)
Public Function IVBCallBack_VBCallBackFunc() As Long
MsgBox ("Callback")
End Function
Be sure to have a method on the .NET side to clean up and release all your references since .NET is holding a reference to the VB6 object.
One other thing to note. DO NOT CALL BACK INTO VB6 ON ANY THREAD OTHER THAN THE MAIN UI THREAD!
Upvotes: 3