【问题标题】:How do you bypass a FormClosing event in vb.net?如何绕过 vb.net 中的 FormClosing 事件?
【发布时间】:2014-07-28 07:55:42
【问题描述】:

在我的 mdiMain 中,我有这个代码集。

Private Sub mdiMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    e.Cancel = IIf(MsgBox("Closing this window will log you out. Are you sure?", MsgBoxStyle.YesNo, "Log out?") = MsgBoxResult.Yes, False, True)
End Sub

我这样做的原因是捕获所有关闭表单的触发器。如果用户单击注销按钮,或者他们按下窗口右上角的 x 按钮,或者即使他们按下 Alt-F4。在同一个MDI的FormClosed下,确认退出后有一组指令。我的问题是我还有一个过程,用户被强制退出程序。由于用户被“强制”注销,因此应绕过确认对话框。但是不知道怎么绕过FormClosing事件,直接跳到FormClosed

到目前为止,我只提出了一种方法,那就是设置一个布尔触发器。类似的东西

Private Sub mdiMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    If ForceLogOut = True Then Exit Sub
    e.Cancel = IIf(MsgBox("Closing this window will log you out. Are you sure?", MsgBoxStyle.YesNo, "Log out?") = MsgBoxResult.Yes, False, True)
End Sub

但是为了知识,我仍然想听听其他人的其他方法。

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    您可以查看FormClosingEventArgs.CloseReason 以了解表单关闭的原因,即是什么事件导致表单关闭并相应地设置取消标志。

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        Select Case e.CloseReason
            Case CloseReason.TaskManagerClosing
                e.Cancel = False
            Case CloseReason.MdiFormClosing
                e.Cancel = If(MsgBox("Closing this window will log you out. Are you sure?", MsgBoxStyle.YesNo, "Log out?") = MsgBoxResult.Yes, False, True)
                'etc
        End Select
    End Sub
    

    注意:您应该在 VB.NET 中使用 IfOperator 而不是 IIf 函数,因为它是类型安全的。您还应该打开选项 strict (顺便说一下,出于这个原因,这将不允许您使用 IIf

    【讨论】:

    • 感谢您的回答。我一回家就测试一下。 CloseReason 真的很有趣。我想知道我是否可以使用按钮等表单对象?例如。 CloseReason.btnClose我对IIf这样的一行代码有这种癖好,但为什么它不安全呢?
    • 不,你不能,关闭的原因是枚举。每个值的解释在这里:msdn.microsoft.com/en-us/library/…
    • @YinYangKim - If operator 优于 IIf function,因为它是真正的 operator,并且可以正确短路.它会让你保持你的“瘾”。
    猜你喜欢
    • 1970-01-01
    • 2012-04-10
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多