VB.NET中退出确认的实现

时间:2022-05-28 23:40:51

1、
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    If MessageBox.Show("确定退出吗?", "退出确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
        e.Cancel = True
    End If
End Sub

2、
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    If MsgBox("确定退出吗?", MessageBoxButtons.OKCancel, "退出确认") = Windows.Forms.DialogResult.Cancel Then
        e.Cancel = True
    End If
End Sub
    
    
3、
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    Dim p As Integer
    p = MsgBox("你真的要退出游戏吗?", MsgBoxStyle.OkCancel, "游戏提示")
    If p = 2 Then
        e.Cancel = True
    End If
End Sub

4、最简单的代码:
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
     If MsgBox("你确认要退出程序吗?", MsgBoxStyle.OkCancel, "退出提示") = MsgBoxResult.Cancel Then e.Cancel = True
End Sub

以上只是点击窗口关闭按钮时的用法,若直接在窗体控件上点击退出时,可以用以下方式实现:

    Public Sub checkExit()
        If (MessageBox.Show("您确定要退出系统吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.OK) Then
            Me.Close()
            Application.Exit()
        End If
    End Sub