Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a callback in VB6?

Tags:

callback

vb6

How do you write a callback function in VB6? I know AddressOf gets you the function gets the address in a Long. But how do I call the function with the memory address? Thanks!

like image 287
Perishable Dave Avatar asked Nov 12 '10 21:11

Perishable Dave


2 Answers

This post on vbforums.com gives an example of how to use AddressOf and the CallWindowProc function to execute a callback procedure.

Code from the post:

Private Declare Function CallWindowProc _
 Lib "user32.dll" Alias "CallWindowProcA" ( _
 ByVal lpPrevWndFunc As Long, _
 ByVal hwnd As Long, _
 ByVal msg As Long, _
 ByVal wParam As Long, _
 ByVal lParam As Long) As Long

Private Sub ShowMessage( _
 msg As String, _
 ByVal nUnused1 As Long, _
 ByVal nUnused2 As Long, _
 ByVal nUnused3 As Long)
    'This is the Sub we will call by address
    'it only use one argument but we need to pull the others
    'from the stack, so they are just declared as Long values
    MsgBox msg
End Sub

Private Function ProcPtr(ByVal nAddress As Long) As Long
    'Just return the address we just got
    ProcPtr = nAddress
End Function

Public Sub YouCantDoThisInVB()
    Dim sMessage As String
    Dim nSubAddress As Long

    'This message will be passed to our Sub as an argument
    sMessage = InputBox("Please input a short message")
    'Get the address to the sub we are going to call
    nSubAddress = ProcPtr(AddressOf ShowMessage)
    'Do the magic!
    CallWindowProc nSubAddress, VarPtr(sMessage), 0&, 0&, 0&
End Sub 
like image 169
C-Pound Guru Avatar answered Nov 02 '22 22:11

C-Pound Guru


I'm not sure exactly what you're trying to do.

To invert control, just create the callback function in a class. Then use an instance of the class (an object) to make the callback.

  • If you need to switch between different routines at run time, have separate classes that implement the same interface - a strategy pattern.
  • IMHO AddressOf is far too complicated and risky to use in this way.

AddressOf should only be used if you need to register callback functions with the Windows API.

like image 31
MarkJ Avatar answered Nov 02 '22 20:11

MarkJ