Search code examples
vb.netactionparentshowdialoganonymous-delegates

How to use delegates with Application.OpenForms in a different thread


Here is the code I got up to and it has no errors but it doesn't seem to work. Can somehow tell me whats wrong with it?

        Dim frmCurrentForm As Form
        Dim wasFocused As Boolean = False

        For Each frmCurrentForm In Application.OpenForms
            If Not frmCurrentForm Is Nothing Then
                Dim action As Action(Of Form)
                action = Sub(form)
                             If form.Focused() Then
                                 Dim failedLoginForm As New frmFailedLogin
                                 failedLoginForm.setError("failed blah blah")
                                 'failedLoginForm.Parent = form
                                 failedLoginForm.StartPosition = FormStartPosition.CenterParent
                                 failedLoginForm.ShowDialog()
                                 wasFocused = True
                             End If
                         End Sub

                If (frmCurrentForm.InvokeRequired) Then
                    frmCurrentForm.Invoke(action, New Object() {frmCurrentForm})
                Else
                    action(frmCurrentForm)
                End If

                If wasFocused Then
                    Exit For
                End If
            End If
        Next

Solution

  • Rather than using Focused, which I don't think works very well for Forms, try using Form.ActiveForm:

        Dim frmCurrentForm As Form
    
        frmCurrentForm = Form.ActiveForm
        If Not frmCurrentForm Is Nothing Then
            Dim action As Action(Of Form)
            action = Sub(form)
                         Dim failedLoginForm As New Form2
                         failedLoginForm.setError("failed blah blah")
                         failedLoginForm.StartPosition = FormStartPosition.CenterParent
                         failedLoginForm.ShowDialog(form)
                     End Sub
    
            If (frmCurrentForm.InvokeRequired) Then
                frmCurrentForm.Invoke(action, New Object() {frmCurrentForm})
            Else
                action(frmCurrentForm)
            End If
        End If