Bring MDIChild form to front if already open

OMGSOMETAL picture OMGSOMETAL · Aug 11, 2014 · Viewed 7.6k times · Source

I've been struggling to get this to work...I have a button on a MDIchild form that opens another MDIchild form, but if the form is already open, it does not recognize it and opens a new one instead of bringing it to front. This is the code i've got:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    Dim MDIForm4 As New Form4
    MDIForm4.MdiParent = Me
    MDIForm4.Show()

End Sub

This works for the button to open the new form, and then I tried adding this:

    If Not Form4 Is Nothing Then
        Form4.BringToFront()
    End If

But with no positive outcome. Does someone have any ideas?

Regards,

Jorge Brito

Answer

Steve picture Steve · Aug 11, 2014

Here is how I typically do that:

For Each f As Form In Application.OpenForms
  If TypeOf f Is frmTest Then
    f.Activate()
    Exit Sub
  End If
Next

Dim myChild As New frmTest 
myChild.MdiParent = Me
myChild.Show()

Notice this uses Application.OpenForms, you can use your Me.MdiChildren (assuming Me = this MDI form) if you want just the children of your main form.