Close all open forms except the main menu in C#

前端 未结 8 1831
终归单人心
终归单人心 2020-12-16 14:27

Trying to close all forms except for the main menu using

FormCollection formsList = Application.OpenForms;

with a foreach loop and saying,

相关标签:
8条回答
  • 2020-12-16 15:21

    as the form collection is updating for every iteration. When you close a form, it is removed from the form collection. it's like removing a object from memory while it is using .

    0 讨论(0)
  • 2020-12-16 15:25

    Here's an even more concise method that uses the same number of lines as your original method:

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

    By using Linq's extension method Cast, you can avoid looping through the collection to build an array.

    0 讨论(0)
提交回复
热议问题