방법: 응용 프로그램의 모든 열려 있는 폼에 액세스(Visual Basic)

이 예제에서는 My.Application.OpenForms 속성을 사용하여 응용 프로그램에서 열려 있는 모든 폼의 제목을 표시합니다.

My.Application.OpenForms 속성은 폼을 연 스레드에 관계없이 현재 열려 있는 모든 폼을 반환합니다. 이것은 액세스하기 전에 각 폼의 InvokeRequired 속성을 확인해야 함을 의미합니다. 그렇지 않으면 InvalidOperationException 예외가 throw될 수 있습니다.

이 예제에서는 스레드로부터 안전하게 각 폼의 제목을 가져오는 함수를 선언합니다. 먼저 폼의 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 Forms 컨트롤 호출

참조

OpenForms