Trying to close all opened forms in visual basic

情到浓时终转凉″ 提交于 2019-12-12 14:55:34

问题


I want it so when my button is clicked, I exit my application. I tried a simple for loop:

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

But after closing all forms besides the form with this button on it, I get this error:

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

I believe this is because I close the form executing the code before the loop can go to the next form. If this is the case, how can I make it so my loop finishes once the last form is closed? Can I even do that?


回答1:


Close all but current form:

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

Close application normally:

Application.Exit()

Force application to exit:

Environment.Exit(1)



回答2:


This is simple, just add a validation:

        For Each Form In My.Application.OpenForms
            If Form.name <> Me.Name Then
                Form.Close()
            End If
        Next


来源:https://stackoverflow.com/questions/34845202/trying-to-close-all-opened-forms-in-visual-basic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!