使用选项yes / no阻止Windows窗体关闭

时间:2014-06-06 16:11:51

标签: vb.net

我想为用户提供在后台运行应用程序或在单击表单的关闭按钮时永久关闭它的选项。此时,当用户单击“是”时,会再次出现对话框,当第二次单击“是”时,应用程序将退出。有什么想法是错的吗?

Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) 
  Handles Me.FormClosing

    Dim result = DialogResult = MessageBox.Show("Would you like the backup tool 
 to run in the background?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)

    If result = True Then
        e.Cancel = True
        Me.Hide()
    ElseIf result = False Then
        Application.Exit()
    End If
End Sub

1 个答案:

答案 0 :(得分:4)

您正在将Form.DialogResult与MessageBox.Show()的返回值进行比较。它永远是假的。这使您调用Application.Exit(),再次触发FormClosing事件。正确的代码应该看起来像:

Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
    Dim result = MessageBox.Show("Would you like the backup tool to run in the background?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
    If result = DialogResult.Yes Then
        e.Cancel = True
        Me.Hide()
    End If
End Sub

Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
    Application.Exit()   '' Not that clear that this is really necessary!!
End Sub

请注意,除非您添加代码以重新启动,否则您有一个隐藏的窗口,用户无法轻松返回。