將資料傳遞迴事件源
使用通過引用傳遞的引數
事件可以定義要返回給呼叫者的 ByRef
引數:
Public Event BeforeSomething(ByRef cancel As Boolean)
Public Event AfterSomething()
Public Sub DoSomething()
Dim cancel As Boolean
RaiseEvent BeforeSomething(cancel)
If cancel Then Exit Sub
'todo: actually do something
RaiseEvent AfterSomething
End Sub
如果 BeforeSomething
事件有一個處理程式將其 cancel
引數設定為 True
,那麼當執行程式從處理程式返回時,cancel
將是 True
而 AfterSomething
將永遠不會被引發。
Private WithEvents foo As Something
Private Sub foo_BeforeSomething(ByRef cancel As Boolean)
cancel = MsgBox("Cancel?", vbYesNo) = vbYes
End Sub
Private Sub foo_AfterSomething()
MsgBox "Didn't cancel!"
End Sub
假設 foo
物件引用是在某處分配的,當 foo.DoSomething
執行時,一個訊息框提示是否取消,第二個訊息框僅在 No 選中時顯示未取消 。
使用可變物件
你也可以傳遞一個可變物件 ByVal
的副本,並讓處理程式修改該物件的屬性; 然後,呼叫者可以讀取修改後的屬性值並相應地執行操作。
'class module ReturnBoolean
Option Explicit
Private encapsulated As Boolean
Public Property Get ReturnValue() As Boolean
'Attribute ReturnValue.VB_UserMemId = 0
ReturnValue = encapsulated
End Property
Public Property Let ReturnValue(ByVal value As Boolean)
encapsulated = value
End Property
結合 Variant
型別,這可以用來建立非常明顯的方法來將值返回給呼叫者:
Public Event SomeEvent(ByVal foo As Variant)
Public Sub DoSomething()
Dim result As ReturnBoolean
result = New ReturnBoolean
RaiseEvent SomeEvent(result)
If result Then ' If result.ReturnValue Then
'handler changed the value to True
Else
'handler didn't modify the value
End If
End Sub
處理程式看起來像這樣:
Private Sub source_SomeEvent(ByVal foo As Variant) 'foo is actually a ReturnBoolean object
foo = True 'True is actually assigned to foo.ReturnValue, the class' default member
End Sub