Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to let my program know which form is opened and then do some specific action for that form. Forms are opened in a main-window with an overview and the user can click on an image to open a new form. This main-window is not my BaseForm for the forms I want to open.

To check what form is open, I tried the following code:

C#
private void FormCheck()
        {
            foreach (Form form in Application.OpenForms)
            {
                if (form is thisOne)
                {
                    thisOne = true;
                    theOtherOne = false;
                    hollow = false;
                    break;
                }
                if (form is theOtherOne)
                {
                    theOtherOne = true;
                    thisOne = false;
                    hollow = false;
                    break;
                }
            }
        }


I set the form-related booleans to true, so I can use them in another function, something like this:

C#
private void ActionTime()
        {
            if (thisOne)
                Debug.WriteLine("ThisOne is open");
            if (theOtherOne)
                Debug.WriteLine("The OtherOne is open");
        }


ActionTime is called on a ClickEvent, but the action never happens... I guess there goes something wrong in the foreach-loop
Posted

1 solution

Please see this code which works if your forms are Form1 and Form2:
C#
bool bForm1Open = false;
bool bForm2Open = false;
private void FormCheck()
{
   bForm1Open = false;
   bForm2Open = false;
   foreach (Form form in Application.OpenForms)
   {
      if (form is Form1)
      {
         bForm1Open = true;
      }
      if (form is Form2)
      {
         bForm2Open = true;
      }
   }
}

private void ActionTime()
{
   if (bForm1Open)
      Debug.WriteLine("ThisOne is open");
   if (bForm2Open)
      Debug.WriteLine("The OtherOne is open");
}
 
Share this answer
 
Comments
Frans Jan 27-Sep-12 7:39am    
Problem is already solved, I'd forgotten to call the FormCheck function...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900