C# – Check if Form is already running
Posted on May 12th, 2010 in C#, Tutorials | 2 Comments »
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.
2 Responses
why not do…
private bool CheckForm(Form f)
{
return(Application.OpenForms.Contains(f))
}
Doesn’t require you to enter a loop, looks cleaner too.
@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