关闭所有打开的表单,除了一些 VB.Net

Close all open forms except for some VB.Net

如标题所示,我试图关闭所有打开的表单,但 VB.Net 中的一些表单除外,但这些表单没有关闭。 这是我使用的代码:

Dim lista As New FormCollection
lista = Application.OpenForms
For Each a As Form In lista
    If Not a.Text = "formLogout" And a.Text = "arresto" And a.Text = "riavvio" And a.Text = "formOpen" Then
        a.Close()
    End If
Next
scrivania.Close()
Me.Close()

谢谢。

If 语句将 return 为真 当所有提供的条件都为真时 ,这是不可能的,因为您将相同的 form.Text 与不同的进行比较值。
请注意,在您的示例中 Not 将仅适用于第一个条件

您可以重写条件如下:

If Not (form.Text = "formLogout" OrElse form.Text = "arresto") Then ..

建议使用表单名称集合,不要关闭

Dim remainOpenForms As New HashSet(Of String)
remainOpenForms.Add("formLogout")
remainOpenForms.Add("arresto")

' Create collection of forms to be closed
Dim formsToClose As New List(Of Form)
For Each form As Form In Application.OpenForms
    If remainOpenForms.Contains(form.Text) = False Then formsToClose.Add(form)
Next

For Each form As Form In formsToClose
    form.Close()
Next

与@Fabio 的回答相同,但没有额外的收集和循环。

    Dim keepOpen As New List(Of String) From {Me.Text, Form2.Text, Form3.Text}
    For index = Application.OpenForms.Count - 1 To 0 Step -1
        If Not keepOpen.Contains(Application.OpenForms(index).Text) Then
            Application.OpenForms(index).Close()
        End If
    Next

我知道已经晚了,但对于某些人来说,这是我的答案

这样做是关闭除“exceptthisform”之外的所有表单

     Dim formNames As New List(Of String)

        For Each currentForm As Form In Application.OpenForms

            If currentForm.Name <> "exceptthisform" Then

                formNames.Add(currentForm.Name)

            End If

        Next

        For Each currentFormName As String In formNames
            Application.OpenForms(currentFormName).Close()

        Next

我用 Fabio 解决方案中的 form.toString 替换了 form.toString,效果非常好!

    Try
        Dim remainOpenForms As New HashSet(Of String)
        remainOpenForms.Add("FormMainMenu")

        Dim formsToClose As New List(Of Form)
        For Each form As Form In Application.OpenForms
            If Not remainOpenForms.Contains(form.Name) Then
                formsToClose.Add(form)
                Debug.Print("closing: " & form.Name)
            Else
                Debug.Print("keep open: " & form.Name)
            End If
        Next

        For Each form As Form In formsToClose
            form.Close()
        Next

        Close()
    Catch ex As Exception
        WriteErrors("FMM: WAN2", ex.ToString)
    End Try

如果您想知道我为什么在之后关闭它:我收到一个 InvalidOperationException 集合已修改。这是我的退出申请模块