Hash

January 28, 2009

C#: Check if a Form is already opened

Filed under: .NET — scarefactor @ 1:38 pm
Tags: , , , , , ,

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.

About these ads

19 Comments »

  1. [...] never created and shown. I have previously written a small note on this topic and gave a solution here which I personally don’t [...]

    Pingback by C# Winforms: Create a Single Instance Form « Hash — February 6, 2009 @ 6:12 pm

  2. If you want to try a Singleton Pattern to keep one instance of the Form, here it is

    http://hashfactor.wordpress.com/2009/02/06/c-winforms-create-a-single-instance-form/

    Comment by hashfactor — February 6, 2009 @ 6:13 pm

  3. Your example was not working for me, the function was ok, but I modified the way check if opened:

    UserForm frm = null;
    if ((frm = (UserForm)IsFormAlreadyOpen(typeof(UserForm))) == null)
    {
    frm = new UserForm();
    frm.Show();
    }
    else
    MessageBox.Show(“Already Opened”);

    Comment by Gonzalo Lebron — June 19, 2009 @ 9:43 am

  4. Excellent!! this works!!

    Comment by Rejitha — June 25, 2009 @ 4:51 pm

  5. here is how i do it:

    bool onsiteopen = false;

    foreach (Form S in Application.OpenForms)
    {
    if (S is “MyForm” )
    {
    onsiteopen = true;

    }

    }
    if (onsiteopen == true)
    {
    MessageBox.Show(“this form is already open.”);
    }

    Comment by Jay Stratemeyer — July 18, 2009 @ 3:43 am

  6. oops i left some out….

    bool FormOpen= false;
    foreach (Form
    S in Application.OpenForms)
    {
    if (S is MyForm)
    {
    FormOpen= true;

    }

    }
    if (FormOpen== true)
    {
    MessageBox.Show(“Form already open.”);
    }
    else
    {
    Form MyForm= new MyForm();
    OnSite.Show();

    }

    Comment by Jay Stratemeyer — July 18, 2009 @ 3:45 am

  7. if (newFrmReports.IsMdiChild && newFrmReports.IsDisposed==false)
    {

    newFrmReports.WindowState = FormWindowState.Normal;
    newFrmReports.BringToFront();
    }
    else
    {

    newFrmReports = new frmReports();
    newFrmReports.MdiParent = this;
    newFrmReports.Show();

    }

    Comment by Luis — August 17, 2009 @ 8:40 pm

  8. Thanks man, Nice Coding. I used Like This,

    Form TaskFormName;
    if ((TaskFormName = IsFormAlreadyOpen(typeof(MyForm))) == null)
    {
    TaskFormName = new MyForm(null);
    if (ActiveForm != null) TaskFormName.MdiParent = ActiveForm;
    TaskFormName.Show();
    }
    else
    {
    TaskFormName.WindowState = FormWindowState.Normal;
    TaskFormName.BringToFront();
    }

    Comment by Ravindr.pc — August 19, 2009 @ 4:04 pm

  9. Thanks Gonzalo, it works for me

    Comment by SSK Sorgulama — November 10, 2009 @ 5:59 pm

  10. You can also use Application.OpenForms[string]
    where string is the name of your class

    You may want to store this in a const so you only have to change it once in case the class name changes

    public static bool IsFormRunning()
    {
    Form f = Application.OpenForms["Form1"];

    return f != null;
    }

    Comment by Mike — January 27, 2010 @ 4:33 am

  11. Thanks Gonzalo Lebron.. Its working

    Comment by Ashok — February 25, 2010 @ 10:14 pm

  12. Love it!! Worked for me like heaven!! i was searching for it since 3 dayss!!!

    Thanks a lot!!

    Comment by Aman S. Aneja — March 21, 2010 @ 7:54 pm

  13. That’s precisely what I needed!! Thanks a lot!

    Comment by onur — August 5, 2010 @ 1:53 am

  14. The code snippet was very useful. Thanks ton.

    Comment by Rehana — February 9, 2011 @ 5:10 am

  15. kindly provide VB.NET quivalent code for this

    Comment by uday — April 19, 2011 @ 5:32 pm

  16. [...] the form part wasn’t that much of a challenge for me. it only came when i started to code. one major part that i have to look into was to avoid multiple form instances.  i don’t want to have the same form opened twice. i did some research and was able to find this site. [...]

    Pingback by c sharp check if form is already opened « the gravel project — August 9, 2011 @ 5:21 pm

  17. Hi all,
    We have a scenario where in a single form is opened via a multiple menu commands of a MDI Form. However, I have created separate instances of that form. But, there is method, that checks if the form is open as under:
    private bool IsMDIChildFormOpen(string formName)
    {
    try
    {
    foreach (Form childForm in this.MdiChildren)
    {
    if (childForm.Name == formName)
    {
    if (childForm == null || childForm.IsDisposed)
    return false;
    else
    return true;
    }
    }
    }
    catch (Exception ex)
    {
    PowerTraderException.WriteCustomError(“IsMDIChildFormOpen() : ” + ex.StackTrace);
    throw ex;
    }
    return false;
    }

    and in the menu command handler we check it using:

    private void frmMainToolStripMenuItem_Click(object sender, EventArgs e)
    {
    try
    {

    if (!IsMDIChildFormOpen(“frmMyForm”))
    {
    objMyForm = new frmMyForm();
    objMyForm.MdiParent = this;
    objMyForm.Show();
    }
    else
    {
    if (IsMDIChildFormOpen(“frmMyForm”))
    {
    objMyForm.BringToFront();
    }
    }
    }
    catch (Exception ex)
    {

    }
    }

    It works for all other forms, except one where the same form is opened from 5 different menu command handlers. I want a mechanism to differentiate these instances of the same form and identify which one is open and which instance should be newed.

    Any pointers are much appreciated.

    Thanks.

    Comment by Bhushan — March 14, 2012 @ 3:45 pm

  18. Thanks.
    All of you.
    useful discussion

    Comment by Naresh Parmar — March 16, 2013 @ 8:28 pm

  19. thanks buddy
    its work good.

    Comment by viral — May 14, 2013 @ 10:37 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Rubric Theme. Create a free website or blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: