views:

262

answers:

3

Alright, so I need a method that traverses all the forms inside a VB.net project under Visual Studio 2008, and create an array of type form with references to all the forms inside it, so that the array looks like this (pseudocode)

FormsArray() = [Form1, Form2, Form3, Form4]

However, I don't have a clue as to how to begin. Any help?

Thanks!

A: 

2 options

  1. I would load the actual project file into a XML reader. Then iterate all the nodes looking for all Form SubTypes and store the linked files in an array. If the name of file matches the name of the form class, you can create your FormsArray from that list. Otherwise you have to load each file and look for the public class definition of the file to get the list.

  2. Using Reflection, examine the project using Assembly.GetTypes. Find all the System.Windows.Forms.Form Types and store them in a list. Then write out the Type.Name.

JDMX
-1: "I would load the actual project file into a XML reader", the proper way would use VSTA, as Timores shows.
AMissico
A: 

You need to either write a VS macro or an Addin.

In it, from a DTE or DTE2 instance, you can write:

Public Sub GetForms(ByVal host As DTE2)

    Dim project As Project = host.ActiveDocument.ProjectItem.ContainingProject
    For Each ce As CodeElement In project.CodeModel.CodeElements

        If ce.Kind = vsCMElement.vsCMElementClass Then

            Dim cl As CodeClass = CType(ce, CodeClass)
            If cl.IsDerivedFrom("System.Windows.Forms) Then

                ' do something
            End If
        End If
    Next
End Sub
Timores
A: 

Here is how you would do this using Reflection, assuming that the class where you placed this code was in the same assembly that you wanted to iterate over. If not, then you'll need to change the Me.GetType().Assembly in the For Each loop into something else to account for loading the assembly in a different manner.

Dim Forms As New List(Of Form)()
Dim formType As Type = Type.GetType("System.Windows.Forms.Form")

For Each t As Type In Me.GetType().Assembly.GetTypes()
    If t.IsSubclassOf(formType) = True Then
        Forms.Add(CType(Activator.CreateInstance(t), Form))
    End If
Next
Nick