开发者

How to write a callback in VB6?

How do you write a开发者_如何学Python 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!


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 


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜