Single Instance of Child Forms in MDI Applications
- by Akshay Deep Lamba
In MDI application we can have multiple forms and can work with multiple forms i.e. MDI childs at a time but while developing applications we don't pay attention to the minute details of memory management. Take this as an example, when we develop application say preferably an MDI application, we have multiple child forms inside one parent form. On MDI parent form we would like to have menu strip and tab strip which in turn calls other forms which build the other parts of the application. This also makes our application looks pretty and eye-catching (not much actually). Now on a first go when a user clicks a menu item or a button on a tab strip an application initialize a new instance of a form and shows it to the user inside the MDI parent, if a user again clicks the same button the application creates another new instance for the form and presents it to the user, this will result in the un-necessary usage of the memory. Therefore, if you wish to have your application to prevent generating new instances of the forms then use the below method which will first check if the the form is visible among the list of all the child forms and then compare their types, if the form types matches with the form we are trying to initialize then the form will get activated or we can say it will be bring to front else it will be initialize and set visible to the user in the MDI parent window. The method we are using:
private bool CheckForDuplicateForm(Form newForm)
{
bool bValue = false;
foreach (Form frm in this.MdiChildren)
{
if (frm.GetType() == newForm.GetType())
{
frm.Activate();
bValue = true;
}
}
return bValue;
}
Usage: First we need to initialize the form using the NEW keyword
ReportForm ReportForm = new ReportForm();
We can now check if there is another form present in the MDI parent. Here, we will use the above method to check the presence of the form and set the result in a bool variable as our function return bool value.
bool frmPresent = CheckForDuplicateForm(Reportfrm);
Once the above check is done then depending on the value received from the method we can set our form.
if (frmPresent)
return;
else if (!frmPresent)
{
Reportfrm.MdiParent = this;
Reportfrm.Show();
}
In the end this is the code you will have at you menu item or tab strip click:
ReportForm Reportfrm = new ReportForm();
bool frmPresent = CheckForDuplicateForm(Reportfrm);
if (frmPresent)
return;
else if (!frmPresent)
{
Reportfrm.MdiParent = this;
Reportfrm.Show();
}