关闭除某些VB.Net以外的所有打开的窗体

时间:2019-01-01 18:40:25

标签: vb.net winforms openform

作为标题,我正在尝试关闭所有打开的表单,但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()

Grazie。

4 个答案:

答案 0 :(得分:2)

与@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

答案 1 :(得分:1)

If语句将在所有提供的条件都为true的情况下返回true。,这是不可能的,因为您将相同的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

答案 2 :(得分:0)

我知道已经很晚了,但对于某些问题,这是我的答案

此操作将关闭除“ 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

答案 3 :(得分:0)

我将 form.toString 替换为 form.Name 来自 Fabio 的解决方案,它的效果非常棒!

    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 集合已被修改。这是我的退出应用模块