【问题标题】:Keep form opened if cancel button clicked VB2012如果单击取消按钮,请保持表单打开 VB 2012
【发布时间】:2014-08-10 13:05:15
【问题描述】:

我想知道我可以在下面第一个 if 语句的第二部分输入什么代码,以便在单击取消按钮时保持表单处于活动状态。

Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
    'Message prompt to ask if the user really want to exit
    MsgBox("Are you sure you want to exit?", MsgBoxStyle.OkCancel, "MDCS")

    If MsgBoxResult.Ok Then
        If Application.OpenForms().OfType(Of Find_Client).Any Or Application.OpenForms().OfType(Of Form_items).Any Then
            MsgBox("Close all opened windows before the main", MsgBoxStyle.OkOnly, "MDCS")
        Else
            ' Call sub that close the program
            Me.Close()
            Dim items As New Form_items, clients As New Find_Client
            items.Close()
            clients.Close()
            'Stop Stopwatch
            Timer1.Stop()
            Me.StopWatch.Stop()

            'Mark Stopwatch value
            intTimerValues = Val(Timer_Label.Text)
        End If
    Else
        ???
    End If
End Sub

【问题讨论】:

  • 你是怎么调用函数的?
  • exit_program。我在退出按钮中调用它来关闭应用程序。当单击取消按钮时,应该有可能退出程序。
  • 您没有向我们展示任何实际退出程序的代码。
  • 将代码放入表单的Closing 事件中,如果您的表单不应关闭,请通过 ClosingEventArgs 取消它:e.Cancel = True
  • 他说代码应该放在 Form_Closing 事件中。

标签: vb.net winforms


【解决方案1】:

您的代码不正确。

你显示一个消息框

'Message prompt to ask if the user really want to exit
MsgBox("Are you sure you want to exit?", MsgBoxStyle.OkCancel, "MDCS")

但你不测试它的返回值。

实际上做的是测试一个常量的值,MsgBoxResult.Ok

If MsgBoxResult.Ok Then

MsgBoxResult.Ok is a member of an enumeration 计算结果为 1。所以基本上,你所拥有的是

If 1 Then

嗯,总是 计算结果为True,所以If 块总是运行。你永远不会到达Else 块。

通过实际测试MsgBox 调用的结果来修复代码:

Dim MsgBoxResult As result = MsgBox("Are you sure you want to exit?", _
                                    MsgBoxStyle.OkCancel, _
                                    "MDCS")
If result = MsgBoxResult.Ok Then
    ' ...
    'Close the form.
    Me.Close()
Else
    ' ...
    ' Don't write code to close the form and it won't be closed.
End If

【讨论】:

    【解决方案2】:

    通常情况下,当前活动的表单应该自动显示,但如果您将代码放在特定的按钮事件处理程序中,则不会在 Else 函数中放置任何代码。 好吧,在阅读了您在上面 cmets 中的回复后,我假设您将代码放入 Form_Closing 事件中,如果是这种情况,那么您应该放入 e.Cancel() 在代码的 Else 部分中。

    【讨论】:

    • 当我将else部分留空时,程序会在单击取消按钮时关闭。
    • 请重新检查代码。编辑器不接受 e.cancel。
    • 我找到了答案。我只需要用 MsgBoxResult.cancel 开始 if 语句
    猜你喜欢
    • 1970-01-01
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2017-10-01
    • 2012-01-28
    • 2021-05-14
    相关资源
    最近更新 更多