尝试关闭Visual Basic中所有打开的表单 [英] Trying to close all opened forms in visual basic

查看:70
本文介绍了尝试关闭Visual Basic中所有打开的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要它,因此当单击我的按钮时,我退出我的应用程序.我尝试了一个简单的for循环:

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:

mscorlib.dll中发生了类型为'System.InvalidOperationException'的未处理异常附加信息:集合已修改;枚举操作可能无法执行.

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?

推荐答案

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

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

正常关闭应用程序:

Application.Exit()

强制退出应用程序:

Environment.Exit(1)

这篇关于尝试关闭Visual Basic中所有打开的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆