2010-11-12 30 views
4

如何在VB6中編寫回調函數?我知道AddressOf讓你的函數獲取Long中的地址。但是,如何使用內存地址調用函數?謝謝!如何在VB6中編寫回調?

+0

你需要什麼回調?這個答案會有很大的不同。 – 2010-11-15 15:18:08

+0

我有一個模塊的功能需要超過幾個週期。我正在考慮使用函數的回調函數讓調用者知道進度。所以我會使用它幾乎就像一個事件,除了從一個功能,而不是一個類。 – 2010-11-15 17:36:56

回答

3

我不知道你想要做什麼。

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

4

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