# Sample C# code for single instance of form



## Kreij (Jul 11, 2007)

Ok, besides having only a single instance of an application run, it may be useful (and prudent) to only allow a user to open a single instance of a form. 

Let's say that you have an initial form that contains a button (or whatever) that opens another form. If you click the button again, the default behavior is to open another copy of the form. If you don't want this behavior, read on ....

Again, I am only including relevant code, not all the underlying stuff. If you need more information just holler.

A form normally gets created something like this ...


```
namespace WindowsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponents();
        }
    }
}
```

To make the form a single instance form just change to the following ...


```
namespace WindowsApplication1
{
    // add a private static instance of the form
    private static Form2 mInst;

    // make the form's constructor private
    private Form2()
    {
        InitializeComponents();
    }

    // Create a public static property that returns the state of the instance
    public static Form2 CheckInst
    {
        get
        {
            return mInst;
        }
    }

    // Create a public static property that will create an instance of the form and return it
    public static Form2 CreateInst
    {
        get
        {
            if (mInst == null)
                mInst = new Form2();
            return mInst;
        }
    }

    // We also need to override the OnClose event so we can set the Instance to null

    protected override void OnClose (EventArgs e)
    {
        mInst = null;
        base.OnClose(e);   // Always call the base of OnClose !
    {
}
```

Notice that an Instance of Form2 can *only* be created by calling the public property Form2.CreateInst

Now it is a simple thing to call Form2 from Form1's button so it checks to see if the form is already open and sets it's windows state to normal, brings it to the front and gives it the focus.

Form1 button click event code snippet

```
//When the button is pressed ...
private void button1_Click(object sender, EventArgs e)
{
    // If Form2 is not already open
    if (Form2.CheckInst == null)
    {
        Form2.CreateInst.Show();  // This creates and displays Form2
    }
    else
    {
        // These two lines make sure the state is normal (not min or max) and give it focus.
        Form2.CreatInst.WindowState = FormWindowState.Normal;
        Form2.CreateInst.Focus;
    }
}
```

You could actually eliminate the CheckInst property and just use the CreateInst (as it will not create a Instance if one exists), but having them seperate allows for modification like sending parameters to the form if need be.

Ok, that wraps up my little form adventure.
Any questions ?


----------

