Hash

C#: Check if a Form is already opened

January 28, 2009 · 9 Comments

During WinForms programming you might (chances are that you SHALL) come across a situation where you do not want to open a form multiple times on an event.  A common practice in the event handler function is:

UserForm UForm = new UserForm();
UForm.Show();

This will open your form, fine! But what if the event happens again and the previously opened UserForm has not been closed yet? A new UserForm will be opened and this will go on if the user loves that event  ^o :|

The prevention strategy is to check whether the form is already opened or not.

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

   return null;
}

This little function will help in determining if a particular form is already opened or not.  You can open it or focus it later.

UserForm UForm = null;
if ((UForm = IsFormAlreadyOpen(typeof(UserForm)) == null)
{
    UForm = new UserForm();
    UForm.Show();
}
else
{
    UForm.DoWhatever(); // may be UForm.Select();
}

This works perfect for me. I don’t like that loop though.

Categories: .NET
Tagged: , , , , , ,

9 responses so far ↓

Leave a Comment