How to avoid multiple instances of windows form in c#

implement the Singleton pattern

an example: CodeProject: Simple Singleton Forms (ok, it's in VB.NET, but just to give you a clue)


Yes, it has singleton pattern,

Code to create a singleton object,

public partial class Form2 : Form
{
 .....
 private static Form2 inst;
 public static Form2  GetForm
 {
   get
    {
     if (inst == null || inst.IsDisposed)
         inst = new Form2();
     return inst;
     }
 }
 ....
}

Invoke/Show this form,

Form2.GetForm.Show();

When you display the dialog simply use .ShowDialog(); instead of .Show();


One solution I applied to my project in order to bring this form again in the foreground is:

    private bool checkWindowOpen(string windowName)
    {
        for (int i = 0; i < Application.OpenForms.Count; i++)
        {
            if (Application.OpenForms[i].Name.Equals(windowName))
            {
                Application.OpenForms[i].BringToFront();
                return false;
            }
        }
        return true;
    }

windowName is essentially the class name of your Windows Form and return value can be used for not creating a new form instance.