How to write a callback in VB6?

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

+4
source share
2 answers

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

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

  • If you need to switch between different procedures at runtime, you have separate classes that implement the same interface - the strategy template .
  • IMHO AddressOf too complex and risky to use in this way.

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

+3
source

This post on vbforums.com provides an example of how to use the AddressOf and CallWindowProc functions to perform a callback procedure.

Code from message:

 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 
+5
source

All Articles