Get ALL the forms into a collection

I am able to get all the open forms into a collection and iterate through them. Is there a way to get all forms, opened and closed Thanks...

Answer this question

Get ALL the forms into a collection

  • evgenypa

    Anytime :)

    What I meant was that you could and probably would be referencing other assemblies. Maybe they also have types that derive from Form. But if you don't need those, then it's best to leave the complexity out of your code.

    Imran.

  • BBach

    As long as the projects are part of the same assembly, you shouldn't have a problem and that code should work. However, if there are other assemblies loaded in the current app domain, you can do this:

    foreach(Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
    {
    foreach(Type type in asm.GetTypes())
    {
    //same stuff as before..
    }
    }


    If you want to get forms in assemblies referenced by your assembly, you can do this:
    foreach(Assembly asm in Assembly.GetExecutingAssembly().GetReferencedAssemblies())
    {
    foreach(Type type in asm.GetTypes())
    {
    //same stuff as before..
    }
    }

    Depending on your requirements, you can use either one or both of those methods.

    hope that helps,
    Imran.

  • T-H

    Well, all I know is the code you gave me returned each of my Forms. This solution is going into a bigger project, so maybe that wouldnt be a bad idea. Could you tell me how to look into all the assemblies.. thanks again.
  • j_e_f_f

    Yes. But that depends on what you mean by 'all forms'. Do you mean all forms in the current assembly or all forms in all the loaded assemblies You can use reflection to get the forms for either of these cases. Here's how you would get them from the current assembly:

    List<Form> allForms = new List<Form>();
    Assembly asm = Assembly.GetExecutingAssembly();

    foreach (Type t in asm.GetTypes())
    {
    if(t is Form)
    {
    allForms.add(t);
    }
    }


    hope that helps,
    Imran.

  • Soso2K

    Thanks for the help. That did what I was looking for. Im not sure what you mean by all forms in all assemblies. The code you provided returned every single form in my solution. What other forms are there in the other assemblies Thanks again, I never, never, never would have figured that out on my own.
  • Get ALL the forms into a collection