How can I make a single instance form (not application)?

Well, the simplest way is to have a static field which stores a reference to the single instance or null, and then a method to retrieve it or create a new one.

Note that this isn’t the same as making it a singleton – because I assume if the form is closed, you’d want to create a new instance next time. (The alternative – hiding it and reusing it – is shown in STO’s answer.) You may want something like this:

public class OptionsDialog : Form
{
    private static OptionsDialog openForm = null;

    // No need for locking - you'll be doing all this on the UI thread...
    public static OptionsDialog GetInstance() 
    {
        if (openForm == null)
        {
            openForm = new OptionsDialog();
            openForm.FormClosed += delegate { openForm = null; };
        }
        return openForm;
    }
}

You may want to make the method perform the “bring it to the front” steps as well, of course.

Leave a Comment