Welcome to Geekdojo Sign in | Join | Help

Jose Luis Manners

.NET and other related technologies

How to enumerate the forms in a project

Someone posted a message in one of the many newsgroups I frequently visit.  He needed to find out at runtime how many Windows forms exist in a project.  Here's the message and my solution to his problem in case anybody else finds it useful:

"Saludos

Estoy haciendo un proyecto WinForm y requiero saber cómo puedo ver las
formas que están dentro del proyecto

Claro , con el explorador en modo diseño, solo que requiero verlas en en
tiempo de corrida. No se si conoces en Access el objeto forms collection que
te muestra las características de las formas de la currentdb, de manera que
yo pudiera recorrer con una instruccion for each... todas y cada una de las
formas y abrir una en particular. En Visual .net yo puedo instanciar una
forma, pero lo hago sabiendo su nombre : no puedo por ejemplo decir
for each frm in forms
  if frm.name='XXXX'
    frm.show
   exit for
endif
next
ya que no existe el objeto forms que me muestre las formas del proyecto.

gracias
"

We can easily obtain this information at runtime using Reflection.  All we have to do is call the GetExecutingAssembly method to obtain an Assembly object that points to the assembly we're executing (our current project), we then call GetTypes on that assembly object to get a list of all the types defined inside of it.  The rest is just looping through the list and check which type(s) match what we're looking for, in this case we're looking for Windows forms:

    Type[] tipos = System.Reflection.Assembly.GetExecutingAssembly().GetTypes(); 

    foreach(Type tipo in tipos)

    {

        if (tipo.BaseType.FullName == "System.Windows.Forms.Form")

        {

            object objeto = Activator.CreateInstance(tipo, true);

            System.Windows.Forms.Form formulario = objeto as System.Windows.Forms.Form;

            formulario.Show();  // do something with the instantiated form

        } 

    }

If anybody has a more elegant, clever, faster, easier, etc., etc., way to do it, I'm all ears.

Published Monday, March 13, 2006 2:40 PM by jmanners
Filed Under: ,

Comments

No Comments

Anonymous comments are disabled
Powered by Community Server, by Telligent Systems