0

我需要能够关闭一个表单并让它关闭除开关板之外的所有其他表单。我尝试使用此代码,但它也关闭了 frmSwitch,即使我尝试对其进行编码以关闭除此之外的所有内容。我哪里做错了?我应该使用表格的实际名称对吗?

Form[] forms = Application.OpenForms.Cast<Form>().ToArray();
foreach (Form thisForm in forms)
    {
        if (thisForm.Name != "frmSwitch") thisForm.Close();
    }
4

2 回答 2

1

您需要检查 if thisForm is frmSwitch,然后关闭其余部分。

foreach (Form thisForm in Application.OpenForms)
{
    if (!(thisForm is frmSwitch))
        thisForm.Close();
}

您也不必使用Cast<Form>and ToArray,您可以枚举FormCollection

于 2013-11-05T13:42:31.253 回答
0

假设您正在关闭“主表单”,这将起作用

var list = Application.OpenForms.Cast<Form>().ToArray();
foreach (Form item in list)
{
    if (item.Equals(this)) continue;
    item.Close();
}
于 2013-11-05T14:34:18.007 回答