Alex Rivera | Logout

How to avoid multiple instances of windows form in c#

Asked 2009-09-10T06:04:32.793
9

How to avoid multiple instances of windows form in c# ?? i want only one instance of the form running. Because there are chances of opening the same form from many pages of my application.

Edit
Report

3 Answers

11

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();
answered 2009-09-10T06:17:07.023
0

Try this code

Public class MyClass
{
    //Create a variable named 
    public static int count = 0;
    //Then increment count variable in constructor
    MyClass()
    {
        count++;
    }
}

While creating the object for the above class 'MyClass' check the count value greater than 1

class AnotherClass
{
    public void Event()
    {
        if(ClassName.Count <= 1)
        {
            ClassName classname=new ClassName();
        }
    }
}
answered 2012-08-07T10:20:30.953
-1

Singletons are not object-oriented. They are simply the object version of global variables. What you can do is to make the constructor of the Form class private, so nobody can accidentally create one of these. Then call in reflection, convert the ctor to public and make sure you create one and only one instance of it.

answered 2009-09-10T08:08:44.070

Your Answer