方法: アプリケーションで開いているすべてのフォームにアクセスする (Visual Basic)

この例では、My.Application.OpenForms プロパティを使用して、アプリケーションで開いているすべてのフォームのタイトルを表示します。

My.Application.OpenForms プロパティは、どのスレッドが開いたフォームかにかかわらず、現在開いているすべてのフォームを返します。 したがって、各フォームにアクセスする前に、その InvokeRequired プロパティをチェックする必要があります。これを行わない場合は、InvalidOperationException 例外がスローされる可能性があります。

この例では、各フォームのタイトルをスレッド セーフな方法で取得する関数を宣言します。 まず、フォームの InvokeRequired プロパティをチェックし、必要がある場合は BeginInvoke メソッドを使用して、関数をそのフォームのスレッドで実行します。 次に、関数はフォームのタイトルを返します。

使用例

この例では、アプリケーションで開いている各フォームをループし、それぞれのタイトルを ListBox コントロールに表示します。 コードを単純にして、現在のスレッドから直接アクセスできるフォームのみを表示する方法については、「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 フォーム コントロールのスレッド セーフな呼び出しを行う

参照

OpenForms