问题描述:

I would like to provide the user the option to either run the application on the background or close it permanently when the form's close button is clicked. At the moment, when the use clicks 'Yes' the dialog box reappears and when clicking yes for a second time the application exits. Any ideas what is wrong?

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

网友答案:

You are comparing the Form.DialogResult with the return value of MessageBox.Show(). It will always be False. Which makes you call Application.Exit(), that fires the FormClosing event again. Proper code ought to look like:

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

Do keep in mind that you've got a hidden window that the user can't get back to easily unless you add code to revive it.

相关阅读:
Top