Introduction
First of all, since this is my first article ever submitted (not only in CodeProject), let me just say that professionally I use older Microsoft technologies, and I have started studying and coding in C# just a couple of months ago. Therefore, I know that the method described here is most probably not the best solution but it served its cause for me. So, if you do have any comments or you can suggest a more efficient way of accomplishing this result, please let me know.
Most of the times, MDI applications are much more time-consuming than the normal SDI applications, and demand the maximum level of the developer's concentration (at least, this is the case with me ;p). This article (code snippet) will try to describe a very simple way of keeping only one instance of each MDI child form opened at all times, during the application's execution.
Background
I faced this problem during the development of a personal project (a dental solution) under C# and VS 2003. I had to make sure that whenever the user tries to open a new instance, the currently open instance will become active instead (or open if none is currently opened).
Using the code
The following snippet supposes that a toolbar exists on the MDI container form. Clicking on toolBarButton1
creates and displays the Patients
form (our MDI child). All of the code goes into the click event of the toolbar:
private void toolBar1_ButtonClick(object sender,
System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
bool found = false;
if (e.Button == toolBarButton1)
{
Form[] charr = this.MdiChildren;
if (charr.Length == 0)
{
Patients myPatients = new Patients();
myPatients.MdiParent = this;
myPatients.StartPosition = FormStartPosition.Manual;
myPatients.Location = new Point(0,0);
myPatients.Show();
}
else
{
foreach (Form chform in charr)
{
if (chform.Name == "Patients")
{
chform.Activate();
found = true;
break;
}
else
found = false;
}
if (found == false)
{
Patients myPatients = new Patients();
myPatients.MdiParent = this;
myPatients.StartPosition = FormStartPosition.Manual;
myPatients.Location = new Point(0,0);
myPatients.Show();
}
}
}
}
History
Up to now, this is the exact solution I have implemented in my project. If I come up with any improvements, I will make sure I will post them. But in the meantime, if you can suggest anything cooler, please let me know.
Thanks.