-1

作为标题,我试图关闭所有打开的表单,除了 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()

格拉齐。

4

4 回答 4

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
于 2019-01-01T19:32:57.387 回答
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
于 2019-01-01T18:55:42.003 回答
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
于 2020-11-14T17:33:50.417 回答
0

我换了形式。带表格的toString 。来自 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 集合已修改。这是我的退出应用程序模块

于 2021-01-05T13:33:39.313 回答