如何在VB6中编写回调?

如何在VB6中编写回调?

问题描述:

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

+0

你需要什么回调?这个答案会有很大的不同。 – 2010-11-15 15:18:08

+0

我有一个模块的功能需要超过几个周期。我正在考虑使用函数的回调函数让调用者知道进度。所以我会使用它几乎就像一个事件,除了从一个功能,而不是一个类。 – 2010-11-15 17:36:56

我不知道你想要做什么。

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

  • 如果您需要在运行时在不同的例程之间切换,请将不同的类实现相同的接口 - strategy pattern
  • 恕我直言AddressOf是太复杂和风险使用这种方式。

AddressOf只有来,如果你需要register callback functions与Windows API使用。

+0

我在主要评论主题上发布了我的意图。但是我会在这里重新发布:在一个模块中有一个函数需要多个循环。我正在考虑使用函数的回调函数让调用者知道进度。所以我会使用它几乎就像一个事件,除了从一个功能,而不是一个类。 – 2010-11-15 17:38:26

+0

糟糕,我忽略了这些评论。那么,你能不能将一个对象传递给该函数,然后回调该对象?或者把这个函数放到一个新的类中,并且从类中引发事件?两者都很干净的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 
+0

像这样使用AddressOf的风险很大。为什么不只是在类中创建回调函数并使用实例(对象)来进行回调? – MarkJ 2010-11-15 15:17:23

+1

...如果你犯了一个错误,你的整个应用程序将死于未处理的异常错误。 – MarkJ 2010-11-15 21:29:15

+0

@MarkJ:我同意。这只是一种做法的例子 - 不一定是我会选择的一种。 – 2010-11-18 22:24:08