使用消息框确认程序关闭

时间:2013-06-26 02:40:59

标签: vb.net

当我按下关闭按钮时会弹出一个消息框,该按钮基本上表示“你确定要退出”,但是当我点击“否”按钮或取消但程序关闭时如何

这是我的代码:

'Close Button
Private Sub BtnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnClose.Click

    Dim result = MessageBox.Show(" Are you sure you want to quit", "Are you sure?", MessageBoxButtons.YesNoCancel)
    Me.Close()

End Sub

8 个答案:

答案 0 :(得分:4)

您对result的价值无效。您需要检查该值并确定是否调用Me.Close()。代码约

If result = DialogResult.Yes Then
    Me.Close()
End If

答案 1 :(得分:3)

如果您正在使用信息框以防止意外表格关闭,您的方法可能无法始终有效。如果用户以任何其他方式关闭应用程序而不是单击“关闭”按钮,则不会显示消息框。

尝试使用FormClosing事件。

'Close Button
Private Sub BtnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnClose.Click
    Me.Close()
End Sub

'FormClosing Event
Private Sub MyForm_Closing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    If MessageBox.Show(" Are you sure you want to quit", "Are you sure?", MessageBoxButtons.YesNoCancel) <> DialogResult.Yes
         e.Cancel = True
    End If
End Sub

答案 2 :(得分:2)

无论Me.Close()是什么,您都会发出result。检查结果并仅在用户点击Me.Close()

时执行Yes

答案 3 :(得分:2)

Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
  If MsgBox("Are you sure you want to quit?", MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2, "Close application") = Windows.Forms.DialogResult.Yes Then
    Me.Close()
  End If
End Sub

答案 4 :(得分:2)

复制此内容:

    Dim result = MessageBox.Show(" Are you sure you want to end the Application", "School Management System", MessageBoxButtons.YesNoCancel)
    If result = DialogResult.Yes Then
        Me.Close()
    End If

答案 5 :(得分:1)

 Dim result = MessageBox.Show(" Are you sure you want to quit", "System Reminder", MessageBoxButtons.YesNo)
    If result = DialogResult.Yes Then
        Me.Close()

    End If

答案 6 :(得分:0)

如果是由于主窗体中的按钮而打开子窗体:

如果MessageBox.Show(&#34;你确定要退出应用程序吗?&#34;,&#34;退出?&#34;,MessageBoxButtons.YesNo)= DialogResult.Yes那么

Me.Hide():MainForm.Show()

    Else
        e.Cancel = True
    End If 

答案 7 :(得分:0)

您可以使用以下代码:

Dim closingfrm = MsgBox(" Are you sure to close", MsgBoxStyle.YesNo)
If closingfrm = DialogResult.Yes Then
Application.Exit()
End If