如何在VB6中编写回调?

时间:2010-11-12 21:06:18

标签: vb6 callback

如何在VB6中编写回调函数?我知道AddressOf让你的函数获取Long中的地址。但是如何用内存地址调用该函数?谢谢!

2 个答案:

答案 0 :(得分:7)

vbforums.com上的

This post给出了一个如何使用AddressOf和CallWindowProc函数来执行回调过程的示例。

帖子中的代码:

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 

答案 1 :(得分:4)

我不确定你到底想要做什么。

invert control,只需在类中创建回调函数即可。然后使用类(对象)的实例进行回调。

  • 如果需要在运行时在不同的例程之间切换,请使用实现相同接口的单独类 - strategy pattern
  • 恕我直言AddressOf过于复杂且风险太大,无法以这种方式使用。
如果您需要register callback functions使用Windows API,

AddressOf