Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preventing multiple instance of one form from displaying

Tags:

c#

forms

window

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();
        } 
like image 528
Brodie Avatar asked Jan 07 '10 04:01

Brodie


People also ask

How do I block multiple instances of an application?

Check the Make Single Instance option in the application properties. Save the project and then build it to create the exe. Then see if you can run 2 instances of the exe.

How can avoid multiple instances of Windows form in C#?

This is to Prevent Multiple Instances for a Particular Form in a Windows Application. This is to Prevent Multiple Instances for a Particular Form in a Windows Application. or try this simple code, Form1 Frm = new Form1();

Can we have multiple interfaces in single form?

A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces.

How do I run a single instance of the application using Windows Forms?

" This feature is already built in to Windows Forms. Just go to the project properties and click the "Single Instance Application" checkbox. "


2 Answers

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.

like image 53
Nate Avatar answered Oct 21 '22 07:10

Nate


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();
     }
}
like image 11
mletterle Avatar answered Oct 21 '22 07:10

mletterle