Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vb.net 遍历Windows窗体并关闭它们?_Vb.net_Winforms_Foreach - Fatal编程技术网

Vb.net 遍历Windows窗体并关闭它们?

Vb.net 遍历Windows窗体并关闭它们?,vb.net,winforms,foreach,Vb.net,Winforms,Foreach,作为清理的一部分,我尝试使用以下代码迭代应用程序中当前打开的所有表单,并关闭它们(主表单除外) Dim openForms As Windows.Forms.FormCollection = Application.OpenForms For Each frm As Windows.Forms.Form In openForms If frm.Name.ToString() <> "FrmMainNew" Then frm.C

作为清理的一部分,我尝试使用以下代码迭代应用程序中当前打开的所有表单,并关闭它们(主表单除外)

    Dim openForms As Windows.Forms.FormCollection = Application.OpenForms

    For Each frm As Windows.Forms.Form In openForms
        If frm.Name.ToString() <> "FrmMainNew" Then
            frm.Close()
        End If
    Next

但是,我得到了一个InvalidOperationException,因为当执行frm.Close时,openForms中的条目被删除,从而改变了集合的大小。我显然做错了什么,所以如果有人能在这里指出问题所在,那就太棒了。否则,有没有其他方法来做类似的事情

向后迭代,以便修改集合时不会出现字节:

    For ix As Integer = Application.OpenForms.Count - 1 To 0 Step -1
        Dim frm = Application.OpenForms(ix)
        '' etc..
    Next

使用while循环而不是For,检查Application.OpenForms.Count>1 当您使用while循环时,您可以在其他事情发生时执行某些操作。您不需要迭代槽集合,它也不会在您身上发生变异。

另一种方法是:

For Each OFORM in Application.Openforms
    With OFORM
        'Methods and conditions here
    End With
Next OFORM