【发布时间】:2016-07-16 06:58:57
【问题描述】:
如何为手动实例化的表单对象捕获 onClose 或 onUnload 事件?
我注意到如果(在我的控制器类中),我使用 WithEvents 关键字标注了一个 Access.Textbox 或 Access.CommandButton 对象,然后 Access VBA IDE 将自动在代码窗口上方的组合框中显示该对象及其可用事件。
但是,如果我使用 WithEvents 关键字标注了一个 Form 对象或自定义 Form 对象,则没有列出对象或可用事件。
Form_Popup_Credentials(表单代码):
Public Event CustomUnLoad()
Private Sub Form_Unload(Cancel As Integer)
RaiseEvent CustomUnLoad
End Sub
FormController 类:
Dim WithEvents Loginfrm As Form_Popup_Credentials
Dim WithEvents Loginbtn As Access.CommandButton
Public Sub GetCredentials()
' If the Popup Credential form is not instantiated,
' then bring it into existence
If Loginfrm Is Nothing Then
Set Loginfrm = New Form_Popup_Credentials
End If
' Set up a reference to the "Login" button
Set Loginbtn = Loginfrm.SignInButton
' Set up the Login Button Click() event
Loginbtn.OnClick = "[Event Procedure]"
' Set up the Login Form's events
Loginfrm.OnUnload = "[Event Procedure]"
Loginfrm.OnClose = "[Event Procedure]"
' Show the form and give it focus
Loginfrm.Visible = True
Loginfrm.SetFocus
End Sub
' Fires Correctly
Private Sub Loginbtn_Click()
MsgBox "Login Button was Clicked"
' If I uncomment this, then the CustomUnLoad() event fires
' DoCmd.Close acForm, Loginfrm.Name, acSavePrompt
Set Loginbtn = Nothing
Set Loginfrm = Nothing
End Sub
' Doesn't Fire
Private Sub Loginfrm_onClose()
MsgBox "Login Form onClose() fired"
Set Loginfrm = Nothing
Set Loginbtn = Nothing
End Sub
' Doesn't Fire
Private Sub Loginfrm_Close()
MsgBox "Login Form Close() fired"
Set Loginfrm = Nothing
Set Loginbtn = Nothing
End Sub
' Doesn't Fire
Private Sub Loginfrm_onUnload()
MsgBox "Login Form onUnload() fired"
Set Loginfrm = Nothing
Set Loginbtn = Nothing
End Sub
' Doesn't Fire
Private Sub Loginfrm_Unload()
MsgBox "Login Form Unload() fired"
Set Loginfrm = Nothing
Set Loginbtn = Nothing
End Sub
' This fires if the user clicks the X button to close the form,
' but not if the controller unloads the Loginfrm object
Private Sub Loginfrm_CustomUnLoad()
MsgBox "Login Form CustomUnLoad() fired"
Set Loginfrm = Nothing
Set Loginbtn = Nothing
End Sub
【问题讨论】:
-
刚试过,
Dim WithEvents Loginfrm As Form为我工作,我看到了事件的控制和列表。但是Dim WithEvents Loginfrm As Form_Popup_Credentials甚至无法编译。如果您需要表单实例中的自定义事件,我建议您查看接口类并以Implements IMyFormEvents之类的形式使用它
标签: forms class ms-access events vba