为实例化的表单对象捕获 onClose 事件

Posted

技术标签:

【中文标题】为实例化的表单对象捕获 onClose 事件【英文标题】:Trap onClose event for instantiated form object 【发布时间】:2016-07-16 06:58:57 【问题描述】:

如何为手动实例化的表单对象捕获 onCloseonUnload 事件?

我注意到如果(在我的控制器类中),我使用 WithEvents 关键字标注了一个 Access.TextboxAccess.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 之类的形式使用它 【参考方案1】:

您必须将您的类级别表单变量声明为Form(或更明确的Access.Form)才能获得Access 表单的标准事件:

Dim WithEvents Loginfrm As Access.Form

顺便说一句,根据 Access 版本,确保将控制器类中的引用设置为 Nothing on Class_Terminate 至关重要。

【讨论】:

我明白我做错了什么。我试图将对象与声明匹配: Dim WithEvents Loginfrm As Access.Form Set Loginfrm = New Access.Form 但只需更改声明即可。谢谢

以上是关于为实例化的表单对象捕获 onClose 事件的主要内容,如果未能解决你的问题,请参考以下文章

更改使用 loadNibNamed 实例化的类

Java 内部是如何处理判断一个对象是不是被实例化的?

java对象实例化的方式

子类对象实例化的全过程

为啥允许向已经实例化的对象添加属性?

Django:RelatedManager 对象是如何实例化的?