Cuthbert Cuthbert - 1 year ago 53 Question

Iterate through Windows forms and close them?

I'm trying to use the following code to iterate over all of the currently open forms in my application and close them except for the main form as part of a clean up.

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

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

However, I'm getting an
because when
is executed, the entry that was in
is deleted, changing the size of the collection. I'm obviously doing something wrong, so if anyone can point me at the problem here, that would be awesome. Otherwise, is there another way to do something like this?


Iterate backwards so that modifying the collection doesn't byte:

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