C# – Check if Form is already running

To check if a form is already running you’ll have to look for it in the Application.OpenForms collection. When a form is opened it is added to that collection.

Here’s a boolean method that checks whether a form is open or not :

private bool CheckForm(Form form)
{
   foreach (Form f in Application.OpenForms)
       if (form == f)
          return true;

 return false;
}

Example use:

// if form2 is not running

if (!CheckForm(form2))
  {
      // do something
  }

Thanks.

If you have any questions, don’t hesitate to post a comment.

5 thoughts on “C# – Check if Form is already running

  1. why not do…

    private bool CheckForm(Form f)
    {
    return(Application.OpenForms.Contains(f))
    }

    Doesn’t require you to enter a loop, looks cleaner too.

  2. @PhonicUK:

    Contains() method is not a member of FormCollection class. That would have been cleaner but there’s no Contains() method for this class.

    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>