views:

159

answers:

5

hello- 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();
        } 
+1  A: 

Depending on how you want to manage this you could do a few things:

  1. Use the Singleton pattern with a global tracking lock that is released when the form is disposed
  2. Manage state in the calling form, and just call "show" if the form has already been launched.
  3. Prelaunch the form, but not show it, that way you manage a single reference and just show it as needed
GrayWizardx
A: 

Try making your Help form global.

private Form help;

private void heToolStripMenuItem_Click(object sender, EventArgs e)
        {
        if(help == null)
          help = new help();

        help.Show();
    }
junmats
downvoter, please explain.
junmats
A: 

Use a Singleton:

class HelpForm : Form
{
   private 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();
     }
}
mletterle
+1  A: 

Alternatively you can use the Application's open forms to see if it is open

btn_LaunchHelp(object o, EventArgs e)
{

   foreach (Form f in Application.OpenForms)
   {
       if (f is HelpForm)
       {
           f.Focus();
           return;
       }
   }

   new help().Show();
}

Edit: To be more clear, this allows the user to close the Help anytime and makes is much easier to manage than saving a reference to the Help window. Nothing to clean up, nothing to maintain.

No longer a user
A: 

Have you considered making an MDI form? This ensures that your parent form is always visible and your child forms are contained within the parent. Then, you need only walk your list of forms and call Show on them. No singletons needed (which many consider to be bad programming practice anyways).

Mystere Man