试图关闭所有在 Visual Basic 中打开的窗体

Trying to close all opened forms in visual basic

我想要它,所以当我的按钮被点击时,我退出我的应用程序。我尝试了一个简单的 for 循环:

Private Sub CloseAllToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CloseAllToolStripMenuItem.Click
    For Each Form In My.Application.OpenForms
        Form.Close()
    Next
End Sub

但在关闭除带有此按钮的表单之外的所有表单后,出现此错误:

An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll Additional information: Collection was modified; enumeration operation may not execute.

我相信这是因为我在循环可以转到下一个表单之前关闭了执行代码的表单。如果是这种情况,我怎样才能做到这一点,以便在最后一个表单关闭后我的循环结束?我能做到吗?

关闭除当前表单之外的所有表单:

My.Application.OpenForms.Cast(Of Form)() _
              .Except({Me}) _
              .ToList() _
              .ForEach(Sub(form) form.Close())

正常关闭应用程序:

Application.Exit()

强制应用程序退出:

Environment.Exit(1)

这个很简单,加个验证就可以了:

        For Each Form In My.Application.OpenForms
            If Form.name <> Me.Name Then
                Form.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