Is there a way to prevent the opening of a certain form within an MDI container if that said form is already opened?
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.
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);
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)