Is there a way to prevent the opening of a certain form within an MDI container if that said form is already opened? Thanks.
A:
logicnp
2009-10-12 08:25:46
+2
A:
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.
Vilx-
2009-10-12 08:27:36
Thread safety should not be a problem, since you only access GUI controls from a single thread.
Groo
2009-10-12 10:18:18
you could have added that this is an implementation of the singleton pattern. I prefer Fredrik Mörk's solution, it does not violate SOC
Johannes Rudolph
2009-10-12 12:01:59
+6
A:
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();
Fredrik Mörk
2009-10-12 08:27:43