Limiting the number of window instances in an MDI application

I want to limit the user to creating multiple instances of the form in an MDI application.

If one instance of this form is open, it should get focus. If this is not a new instance, it must be created.

How can i do this?

+4
source share
3 answers

You can do it as follows.

Create a static method:

public static Form IsFormAlreadyOpen(Type FormType) { foreach (Form OpenForm in System.Windows.Forms.Application.OpenForms) { if (OpenForm.GetType() == FormType) return OpenForm; } return null; } 

And then when you create your child form.

 frmMyChildForm frmChild1; if ((frmChild1 = (frmMyChildForm)IsFormAlreadyOpen(typeof(frmMyChildForm))) == null) { //Form isn't open so create one frmChild1= new frmMyChildForm (); } else { // Form is already open so bring it to the front frmChild1.BringToFront(); } 
+5
source

Maybe something like this can help you

 Form frmToCreate; String strClassName=typeof(FormToCreate).Name frmToCreate = GetForm(strClass); if(frmToCreate == null) { //create the form here } frmToCreate.MdiParent = this; //supposing you are inside of the mainwindow (MDI window) frmToCreate.Visible = true; //other code goes here 

where getform will be something like this

 public Form GetForm(String type) { int i; Form[] children = this.MdiChildren; //or mdiwindow.MdiChildren for (i = 0; i < children.Length; i++) { if (children[i].GetType().Name == type) { return children[i]; } } return null; } 

If you are just playing with the MdiChildren property.

0
source

You can use a singleton-pattern-approach, and let the form have an instance-instance-variable that keeps track of whether it has been initialized or not.

http://en.wikipedia.org/wiki/Singleton_pattern

-1
source

All Articles