如何在VB6中编写回调?
我不知道你想要做什么。
到invert control,只需在类中创建回调函数即可。然后使用该类的一个实例(一个对象)进行回调。
- 如果您需要在运行时在不同的例程之间切换,请将不同的类实现相同的接口 - strategy pattern。
- 恕我直言
AddressOf
是太复杂和风险使用这种方式。
AddressOf
应只有来,如果你需要register callback functions与Windows API使用。
我在主要评论主题上发布了我的意图。但是我会在这里重新发布:在一个模块中有一个函数需要多个循环。我正在考虑使用函数的回调函数让调用者知道进度。所以我会使用它几乎就像一个事件,除了从一个功能,而不是一个类。 – 2010-11-15 17:38:26
糟糕,我忽略了这些评论。那么,你能不能将一个对象传递给该函数,然后回调该对象?或者把这个函数放到一个新的类中,并且从类中引发事件?两者都很干净的OO模式。 VB6中缺少委托的解决方法。 – MarkJ 2010-11-15 21:21:44
This post在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
你需要什么回调?这个答案会有很大的不同。 – 2010-11-15 15:18:08
我有一个模块的功能需要超过几个周期。我正在考虑使用函数的回调函数让调用者知道进度。所以我会使用它几乎就像一个事件,除了从一个功能,而不是一个类。 – 2010-11-15 17:36:56