0

I have window "Child 1", it opens from "Parent". Once I click in menu to open "Child 1" it can open several windows if I click several times in the menu. How to verify if the window "Child 1" opens then we should just bring it up.

The code which I use to open the window:

    var ticketTypesForm = new fTicketTypes();
    ticketTypesForm.Show();
Sergey
  • 7,933
  • 16
  • 49
  • 77

5 Answers5

3

Calling the Application.OpenForms will give you a collection of all your open forms. You can just navigate through each of the open forms to check if Child Form 1 has been created already. If it is just call the .Focus() method to bring it up front. If it has not been created yet, create the form as you would.

lem.mallari
  • 1,274
  • 12
  • 25
  • This [this answer](http://stackoverflow.com/a/3751748/17034) for the trouble with doing this. – Hans Passant Apr 28 '13 at 17:08
  • thanks for the link! didn't know that there was an inherent issue with Application.OpenForms. Thanks for pointing to the right direction. :) – lem.mallari Apr 28 '13 at 17:11
1

Just keep a reference from your class instead creating one everytime.

Luiz Freneda
  • 112
  • 1
  • 5
1

Don't use var, instead you can do this

fTicketTypes ticketTypeForm;
//Some code goes here.
if(ticketTypeForm == null)
    ticketTypeForm = new fTicketTypes();
ticketTypeForm.Show();
Rao Ehsan
  • 778
  • 8
  • 15
  • make sure ticketTypeForm is visible in event handler code if you want to do form opening on some event. – Rao Ehsan Apr 28 '13 at 16:32
1

Before show your new form again, check if its already opened or not using :

Application.OpenForms.OfType<YOUR_FORM_TYPE>().Any())

and if its opened, ignore he command, but if not open it again, you can do the following :

    ticketTypesForm myTicketTypesForm;
    private void OpenDialog(object sender, EventArgs e)
    {
        if (!Application.OpenForms.OfType<ticketTypesForm>().Any())
        {
            if (myTicketTypesForm == null)
                myTicketTypesForm = new ticketTypesForm();
            myTicketTypesForm.Show();
        }
        else
        {
            myTicketTypesForm.Focus();
        }
    }
Amer Sawan
  • 2,126
  • 1
  • 22
  • 40
0
  1. If it is ok for your app to use the child window in Modal mode (you don't need user interaction with parent window ) then just use the child one as Modal. The window is always on top.

    var ticketTypesForm = new fTicketTypes(); ticketTypesForm.ShowDialog(this);

  2. Also your app can close the child window by method Hide() when user closes the window. So the dialog will be never disposed. But in this case you must use the same instance of ticketTypesForm (not creating the new one every time the window is opened )

init app or first displaying

var ticketTypesForm = new fTicketTypes();

show

ticketTypesForm.Show(this);

close

ticketTypesForm.Hide();
Bronek
  • 10,722
  • 2
  • 45
  • 46