Brodie Brodie - 3 months ago 11
C# Question

preventing multiple instance of one form from displaying

I am working on an application in which there is one main form and several other forms that can be used concurrently. when A user clicks to open another form, I'd like to make it so that clicking the button for the form does not open the form up again if it is already open.

showDialog wont work because the user still needs to have access to the controls on the main form.

here is my code for the help window, all the other forms open the same way.

private void heToolStripMenuItem_Click(object sender, EventArgs e)
{
Form help = new help();
help.Show();
}

Answer

Use a Singleton:

class HelpForm : Form
{
   private static HelpForm _instance;
   public static HelpForm GetInstance()
   {
     if(_instance == null) _instance = new HelpForm();
     return _instance; 
   }
}

.......

private void heToolStripMenuItem_Click(object sender, EventArgs e)
{
     HelpForm form = HelpForm.GetInstance();
     if(!form.Visible)
     {
       form.Show();
     }
     else
     {
       form.BringToFront();
     }
}