How to get all forms in a VB.net (VS08) project in an array?

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.


Solution 1:

You have to adjust the function to put the result of msgbox in a array

Public Sub getallforms(ByVal sender As Object)
    Dim Forms As New List(Of Form)()
    Dim formType As Type = Type.GetType("System.Windows.Forms.Form")
    For Each t As Type In sender.GetType().Assembly.GetTypes()
        If UCase(t.BaseType.ToString) = "SYSTEM.WINDOWS.FORMS.FORM" Then
            MsgBox(t.Name)
        End If
    Next
End Sub

You must call the function from any form in the application like this (getallforms(me))

Solution 2:

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

Solution 3:

Hey this is what I did to get the list of forms in my vb project, how ever this in not in code but you could write system.io code fragment to do just that.

  1. open cmd prompt
  2. go to project folder
  3. run a dir /s/b *.designer.vb >> list.txt
  4. use notepad or sublimetext and edit it to get the list ordered as you like it.

:) hope this helped!