如何:访问应用程序中所有打开的窗体

更新:2007 年 11 月

此示例使用 My.Application.OpenForms 属性来显示应用程序的所有打开的窗体的标题。

My.Application.OpenForms 属性返回所有当前打开的窗体,而不考虑由哪个线程打开这些窗体。这意味着您应该在访问每个窗体前检查其 InvokeRequired 属性;否则,它可能引发 InvalidOperationException 异常。

此示例声明一个函数,用于以线程安全方式获取每个窗体的标题。首先,它检查窗体的 InvokeRequired 属性,如果需要,还使用 BeginInvoke 方法在窗体的线程上执行该函数。该函数随后返回窗体的标题。

示例

此示例循环访问应用程序的打开窗体,并在 ListBox 控件中显示这些窗体的标题。有关仅显示可以直接从当前线程访问的窗体的更简单代码,请参见 My.Application.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

请参见

任务

如何:对 Windows 窗体控件进行线程安全调用

参考

My.Application.OpenForms 属性