How to: Access All Open Forms of an Application (Visual Basic)

This example uses the My.Application.OpenForms property to display the titles of all the application's open forms.

The My.Application.OpenForms property returns all currently open forms, regardless of which thread opened them. This means that you should check the InvokeRequired property of each form before accessing it; otherwise it might throw an InvalidOperationException exception.

This example declares a function that obtains each form's title in a thread-safe manner. First, it checks the form's InvokeRequired property and, if necessary, uses the BeginInvoke method to execute the function on the form's thread. Then the function returns the form's title.

Example

This example loops over the application's open forms and displays their titles in a ListBox control. For simpler code that displays only the forms directly accessible from the current thread, see OpenForms.

Private Sub GetOpenFormTitles()
    Dim formTitles As New Collection

    Try
        For Each f As Form In My.Application.OpenForms
            ' Use a thread-safe method to get all form titles.
            formTitles.Add(GetFormTitle(f))
        Next
    Catch ex As Exception
        formTitles.Add("Error: " & ex.Message)
    End Try

    Form1.ListBox1.DataSource = formTitles
End Sub

Private Delegate Function GetFormTitleDelegate(ByVal f As Form) As String
Private Function GetFormTitle(ByVal f As Form) As String
    ' Check if the form can be accessed from the current thread.
    If Not f.InvokeRequired Then
        ' Access the form directly.
        Return f.Text
    Else
        ' Marshal to the thread that owns the form. 
        Dim del As GetFormTitleDelegate = AddressOf GetFormTitle
        Dim param As Object() = {f}
        Dim result As System.IAsyncResult = f.BeginInvoke(del, param)
        ' Give the form's thread a chance process function.
        System.Threading.Thread.Sleep(10)
        ' Check the result.
        If result.IsCompleted Then
            ' Get the function's return value.
            Return "Different thread: " & f.EndInvoke(result).ToString
        Else
            Return "Unresponsive thread"
        End If
    End If
End Function

See Also

Tasks

How to: Make Thread-Safe Calls to Windows Forms Controls

Reference

OpenForms