Preventing Multiples of an MDI Child Form

I ran into an issue with my C# development, in the mdi-child forms being allowed to be opened multiple times. Which for the application I am developing at the moment, is not a good thing.

Having multiples of the same form was confusing some database filtering for other forms.

Having had this issue back in Delphi 3, I racked my brain trying to figure out how to stop this happening in Visual Studio 2012 using C#.

The code below will hopefully be of some help to you, I found many solutions online and some just made things even more confusing.

The code sample below, is in my view the easiest to follow. As you can see, it’s in a Button_Click() method, but it could be anywhere. To adapt to suit your own needs. Simply change (f.Text == “Client Record Manager”) to suite the Text property of your own form, and replace ClientsFrm with the name of your form.

[code lang=”csharp”]private void ClientsBtn_Click(object sender, EventArgs e)
{
bool IsOpen = false;
foreach (Form f in Application.OpenForms)
{
if (f.Text == “Client Record Manager”)
{
IsOpen = true;
f.Focus();
f.WindowState = FormWindowState.Normal;
break;
}
}

if (IsOpen == false)
{
ClientsFrm ClientsFrm = new ClientsFrm();
ClientsFrm.MdiParent = this;
ClientsFrm.Show();
}
}[/code]

About kimberly 190 Articles

I’m an Electronics Service Technician by day. By night I’m an Application Developer, Embedded Software Developer, Mountain Biking chic. Currently starting to put together some home automation projects which I’ll be posting progress on the site.

Be the first to comment

Leave a Reply