Search code examples
c#formswindows-mobilecompact-framework

Switching between multiple forms in C#


I'm developing a C# (compact framework) app which and I need to have 3 forms. I can go from form1 (main) to form2, and from form1 to form3. I also want to be able to switch from form2 to form3. Form3 must be always the same (I need to create it when app starts and close it when app ends).

On form1, on "Go to form 2" button

form2.Show(); form2.BringToFront();

On form1, on "Go to form 3" button

form3.Show(); form3.BringToFront();

On form2, on "Back to form 1"

this.Hide();

On form3, on "Back to form 1"

this.Hide();

But how to switch from form2 to form3 ?

Thank you for any help!


Solution

  • Thanks for the all the contributions! I ended up building a flexible solution that can be extended to many forms.

    When the app starts I create all the required forms. I have an auxiliary class with a (global) variable that holds the current active form (I've used an int but it could be a string with the form name).

    static class GlobalClass
    {
        private static int m_currentActiveForm = 1;
    
        public static int currentActiveForm
        {
            get { return m_currentActiveForm; }
            set { m_currentActiveForm = value; }
        }
    }
    

    On form1 I have included a timer that checks every 100ms the var currentActiveForm. When a change is detected the corresponding form is displayed.

    private void timer2_Tick(object sender, EventArgs e)
        {
    
            if (GlobalClass.currentActiveForm != lastActiveForm)
            {
                switch (GlobalClass.currentActiveForm)
                {
                    case 1:
                        form2.Hide();
                        form3.Hide();
                        this.BringToFront();
                        break;
                    case 2:
                        form2.Show();
                        form2.BringToFront();
                        break;
                    case 3:
                        form3.Show();
                        form3.BringToFront();
                        break;
                 }
           }
    }
    

    Then, on any form, to switch to a new form, I just need to assign a new value to GlobalClass.currentActiveForm which is visible in all forms.