views:

185

answers:

5

How do I prevent Multiple forms from opening?

I do .show on the form but the user can click the main form and the button again and another instance of form opens.

+1  A: 

Two options, depending on what you need:

  1. Use ShowDialog instead of Show, which will open a modal window. This is the obvious solution if you don't need your main form to be active while the child form is open.

  2. Or keep track of the window you opened already in the main form and do nothing if it's already open. This will be needed if you want the user to be able to use the main form while the child form is already open, maybe to open other forms.

Joey
A: 

Disable the main form until the child form goes away, or disable the button.

button_onClick(object Sender, EventArgs e)
{
   Button   btn = sender as Button;
   btn.Enabled = false;
   Form myform = new MyForm();
   myform.Show();
}

Of course, you really should be using form.ShowDialog() rather than form.Show() if you want modal behavior.

John Knoeller
A: 

do something like:

SingleForm myform = null;

void ShowMyForm_Click(object sender, EventArgs e) 
{     if (myform == null)
       {
             myform = new SingleForm();  
        } 
       myform.Show();
       myform.BringToFront(); 
 }
dboarman
this is better, but it doesn't prevent the user from accidently or deliberately bringing the main form to the front again.
John Knoeller
he didn't say that the main form had to stay in the background...he just didn't want the user to be able to open another form when the button was clicked... ;) But thx for the edits...oh...I was misreading I guess. I was thinking there was second form that was opened when a button clicked...idk
dboarman
dboarman
A: 

Force your form object to adhere to the singleton pattern

Andrew Sledge
A: 

I prefer to use Generics and lazy loading to handle my forms. Since all of my forms inherit from a base class, I can use the same method to bring forms to the front, send them to the back, destroy them, start them, etc.

If you keep a form manager class that's responsible for managing any loaded forms, you can bring whatever form to the front that you want, or prevent specific forms from being able to come back unless certain criteria are met.

public void LoadForm<T>() where T : MyNameSpace.MyBaseForm 
{
    // Load all your code in this joint and just call it when you
    // need a form. In here, you can determine if a copy of the form
    // already exists and then bring it forward or not
} 
Joel Etherton