如何在VB6中编写回调?

Per*_*ave 5 vb6 callback

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

C-P*_*uru 7

这个职位上vbforums.com提供了如何要使用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 
Run Code Online (Sandbox Code Playgroud)

  • ...如果你犯了一个错误,整个应用程序将因未处理的异常错误而死亡. (2认同)

Mar*_*rkJ 6

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

反转控制,只需在类中创建回调函数。然后使用类的实例(一个对象)来进行回调。

  • 如果您需要在运行时在不同的例程之间切换,请使用实现相同接口的单独类 - 一种策略模式
  • 恕我直言AddressOf,以这种方式使用过于复杂和冒险。

AddressOf应该只有当你需要使用注册回调函数与Windows API。