vb.net 尝试关闭 Visual Basic 中所有打开的表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34845202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying to close all opened forms in visual basic
提问by Klink45
I want it so when my button is clicked, I exit my application. I tried a simple for loop:
我想要它,所以当我的按钮被点击时,我退出我的应用程序。我尝试了一个简单的 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
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.
mscorlib.dll 中发生类型为“System.InvalidOperationException”的未处理异常附加信息:集合已修改;枚举操作可能无法执行。
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?
我相信这是因为我在循环进入下一个表单之前关闭了执行代码的表单。如果是这种情况,我怎样才能使我的循环在最后一个表单关闭后完成?我什至可以这样做吗?
回答by Reza Aghaei
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)
回答by user8056176
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

