Is there a way to prevent the opening of a certain form within an MDI container if that said form is already opened?
AFAIK there is no standard way. You'll have to implement it yourself. I'd do it this way:
class TheForm: Form
{
private static TheForm Instance;
private TheForm() // Constructor is private
{
}
public static Show(Form mdiParent)
{
if ( Instance == null )
{
// Create new form, assign it to Instance
}
else
Instance.Activate(); // Not sure about this line, find the appropriate equivalent yourself.
}
protected override OnFormClose(EventArgs e)
{
Instance = null;
base.OnFormClose(e);
}
}
If thread safety is of concern, add the appropriate lock
s.
This code work for me in C#
private void btn1_Click(object sender, EventArgs e)
{
Form2 new_form = new Form2();
if (new_form.visible)
new_form.Show();
else
new_form.ShowDialog();
}
This code work for me in vb.net
For Each f As Form In Application.OpenForms
If TypeOf f Is form_name Then
f.Activate()
f.WindowState = FormWindowState.Normal
f.StartPosition = FormStartPosition.WindowsDefaultLocation
f.WindowState = FormWindowState.Maximized
Return
End If
Next
form_name .MdiParent = Me
form_name .Show()
You can interate over the OpenForms collection to check if there is already a form of the given type:
foreach (Form form in Application.OpenForms)
{
if (form.GetType() == typeof(MyFormType))
{
form.Activate();
return;
}
}
Form newForm = new MyFormType();
newForm.MdiParent = this;
newForm.Show();
this code working
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (Form form in Application.OpenForms)
{
if (form.GetType() == typeof(Form2))
{
form.Activate();
return;
}
}
Form2 newForm = new Form2();
newForm.MdiParent = this;
newForm.Show();
}
Though this post is very old, I thought this will add a help.
Need to handle if form is Minimized too. Here is the complete example:
foreach (Form form in this.MdiChildren)
{
if (form.GetType() == typeof(frmMain))
{
if (form.WindowState == FormWindowState.Minimized)
{
form.WindowState = FormWindowState.Normal;
}
form.Activate();
return;
}
}
Form frm = new frmMain();
frm.MdiParent = this;
frm.Show();