你如何绕过vb.net中的FormClosing事件?

时间:2014-07-28 07:55:42

标签: vb.net

在我的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

但是出于知识的考虑,我仍然希望听到其他人关于其他方式的建议。

1 个答案:

答案 0 :(得分:5)

您可以查看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

注意:您应该使用If Operator而不是VB.NET中的IIf函数,因为它是类型安全的。您还应该切换选项严格(由于这个原因,顺便说一下,不允许您使用IIf