作为标题,我正在尝试关闭所有打开的表单,除了一些 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()
格拉齐。
与@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
所有提供的条件都为真时,If
语句将返回 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
它已经晚了,但对于某些人来说,这是我的答案
这样做是关闭除"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
我替换了表单。到带有表单的字符串。法比奥的解决方案中的名字,它就像一个魅力!
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
如果您想知道为什么我在以下之后关闭了它:我收到了一个 无效操作异常集合被修改了。这是我的退出应用程序模块