Question

I have a MDI form. Within this MDI there is multiple button to open new forms. Let buttons are btn1, btn2, btn3, btn4.... When I press btn1, form1 is load. when I press btn2, form2 is load... Now I press btn1, And form1 is loaded. If I press again btn1 then another form1 is open. Simultaneously let form1 is open, if I press btn2 form2 is open. But I want to open a form at a time. How I prevent this?

Was it helpful?

Solution

all the answers you got are good so i'm not going to repeat them, just give you an example of the member and method you can use to prevent that from happening:

  private Form frm;

  private void button1_Clicked(object sender, EventArgs e)
  {
     if (frm != null)
     {
        frm.Close();
        frm.Dispose();
     }

     frm = new Form1();
     frm.Show();
  }

  private void button2_Clicked(object sender, EventArgs e)
  {
     if (frm != null)
     {
        frm.Close();
        frm.Dispose();
     }

     frm = new Form2();
     frm.Show();
  }

OTHER TIPS

You can read up about mutual exclusion http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx It is a general solution to make sure you only have 1 thing (thread, process, form, whatever) of something at the same time. You can even use it inter application. An example is shown here: http://www.dotnetperls.com/mutex

You can create multiple mutexes, one for each form. Or one for a set of forms, in what ever combination suits you.

Example Scenario:

  • Form1 creates a mutex with name X
  • Form2 is being loaded checks whether mutex X is created, if so it closes itself.

Of course you will need to make sure the mutex is Disposed / released when the creator (Form1 in this example) closes, to allow other forms to show.

You can use some flag for this purpose OK, like this:

bool formOpened;
private void buttons_Click(object sender, EventArgs e){
  if(!formOpened){
    //Show your form
    //..............
    formOpened = true;
  }
}
//This is the FormClosed event handler used for all your child forms
private void formsClosed(object sender, FormClosedEventArgs e){
   formOpened = false;
}

At least this is a simple solution which works.

In general case, you need a int variable to count the opened forms, like this:

int openedForms = 0;
//suppose we allow maximum 3 forms opened at a time.
private void buttons_Click(object sender, EventArgs e){
  if(openedForms < 3){
    //Show your form
    //..............
    openedForms++;
  }
}
private void formsClosed(object sender, FormClosedEventArgs e){
  openedForms--;
}

Does this mean while you have Form1 open, you want to still be able to open a Form2 and 3 and etc? It you don't want that, you can use the form1Instance.SHowDialog() instead of Show()... But that generally means you can't access the parent form while form1 is open...

But King King's anwser might be more useable to you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top