24 February 2012

C#: Check if Form is already running

While implementing WinForms programming you might 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:
From1 firstForm = new From1();
firstForm.Show(); 
This will open your form, fine! But what if the event happens again and the previously opened firstForm has not been closed yet? A new firstForm will be opened and this will go on.  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. This code snippet shows you how to check if is your MDI container has a specific MDI child open or not. The sample below looks though each of the mdi children in the container for a instance of the form you want to open. If an instance is found, the form is brought to the front. If an instance of the form is not found, the code opens a new instance of the form.

Boolean Method
To check whether the form is already opened or not      
      private bool CheckForm(Form form)
        {
            form = Application.OpenForms[form.Text];
            if (form != null)
                return true;
            else
                return false;
        }
Example use:
                       Form2 formSecond = new Form2();
                        if (!CheckForm(formSecond ))
                        {
                            formSecond .Show();
                        }
                        else
                        {
                            formSecond .WindowState = FormWindowState.Normal;
                            formSecond .BringToFront();
                            formSecond .Activate();
                        }

2 comments:

  1. Make the CheckForm Method Static
    To check whether the form is already opened or not

    private static bool CheckForm(Form form)
    {
    form = Application.OpenForms[form.Text];
    if (form != null)
    return true;
    else
    return false;
    }

    Secondly, on the Example
    replace formSecond.Show();

    with

    Application.Run(formSecond);

    ReplyDelete