2

I need to open one instance of a MDI child in VB.Net vs2008...this code opens several duplicates of the same MDI child; I got this answer Prevent duplicate MDI children forms for c# but didnt find one for VB.Net vs 2008

Dim myChild As New Form1()
myChild.MdiParent = Me
myChild.Show()
Community
  • 1
  • 1
Wepex
  • 163
  • 4
  • 13
  • 32

3 Answers3

4

This is the VB.Net version of Fredrik Mörk's code:

For Each f As Form In Application.OpenForms
  If TypeOf f Is Form1 Then
    f.Activate()
    Return
  End If
Next

Dim myChild As New Form1
myChild.MdiParent = Me
myChild.Show()
LarsTech
  • 80,625
  • 14
  • 153
  • 225
1

Try this

private void button1_Click(object sender, EventArgs e)
{
   FormCollection fc = Application.OpenForms;
   bool FormFound = false;
   foreach (Form frm in fc)
   {
      if (frm.Name == "Form2")
      {
          frm.Focus();
          FormFound = true;
      }
   }

   if (FormFound == false)
   {
       Form2 f = new Form2();
       f.Show();
    }
}
Nunser
  • 4,512
  • 8
  • 25
  • 37
0

A method can be implemented using Generics (below C# and VB.net options), which can be useful if different MDI Forms need to be opened.

VB.NET

Public Sub Open_MDI(Of T As {New, Form})(bMultipleInstances As Boolean)
    If bMultipleInstances = False Then
        For Each f As Form In Me.MdiChildren
            If TypeOf f Is T Then
                If (f.WindowState = FormWindowState.Minimized) Then
                    f.WindowState = FormWindowState.Maximized;
                End If

                f.Activate()
                Exit Sub
            End If
        Next
    End If

    Dim myChild As New T()
    myChild.MdiParent = Me
    myChild.Show()
End Sub

Use it as follows (indicate False for bMultipleInstances to prevent them)

Open_MDI(Of Form2)(False)

C#

private void OpenMDI<T>(bool multipleInstances)
    where T : Form, new()
{
    if (multipleInstances == false)
    {
        // Look if the form is open
        foreach (Form f in this.MdiChildren)
        {
            if (f.GetType() == typeof(T))
            {
                // Found an open instance. If minimized, maximize and activate
                if (f.WindowState == FormWindowState.Minimized)
                {
                    f.WindowState = FormWindowState.Maximized;
                }

                f.Activate();
                return;
            }
        }
    }

    T newForm = new T();
    newForm.MdiParent = this;
    newForm.Show();
}

Use it as follows (indicate false in multipleInstances to prevent them)

OpenMDI<Form2>(false);
Ricardo González
  • 1,385
  • 10
  • 19