2
votes

So I'm trying to learn a thing or two about coding with c# and something i find quite annoying is the way to switch between forms.

Lets say for a game you want to go to the options panel and when you click the button to get there it closes that window(form1) and opens a new window(form2) for my app.

It doesn't look very nice having windows opening and closing like that so I'm wondering what i can do in order to make it switch from form1 to form2 without closing form1 and not open form2 in a new window (Everything switched on the main window(form1).

Might sound a bit confusing but hopefully you understand what i mean.

The code I'm using so far to switch between forms:

   ChangeOptions optionchanger = new ChangeOptions ();
   this.Hide();
   optionchanger.Show();
2
Can you not group, hide, and show controls so that you have only one window? You can design a UI to have two sets of controls and have them show and hide the sets. One set can be for your game, the other set can be for your options if you don't want to show new windows... - Alexandru
@Alexandru So if i understand this right i can hide/show content of form1 depending on which button i click? - Jim Sundqvist
Jim, yes, you can call .Hide() or .Show() on controls such as the System.Windows.Forms.Label (msdn.microsoft.com/en-us/library/…). That's a very simplistic way of doing it, but I would advise you to group the controls in a Panel or GroupBox like some of the other answers have suggested. - Alexandru
@Alexandru Thanks for the information. I will look into this. - Jim Sundqvist
In addition to the panel/usercontrol solutions, you may wish to research MDI windows. - Sam Axe

2 Answers

2
votes

You could add two panels to a single form, each of which contains the controls you would otherwise have added to one of the two forms. Then switch between the panels by changing their visibility or Z-order. This is slightly tricky in the Windows Forms Designer because you'll have to design the two panels, then position them in the same spot on the containing form.

As @ryanyuyu points out, you can set the Dock property to DockStyle.Fill and switch which panel is on top using Control.BringToFront or Control.SendToBack(). This is also a decent way to interact with the two panels in the designer, as you can switch which is on top from a context menu option.

1
votes

To truly have two forms, your only option is to show a dialog. Hiding your current window is of course optional.

However, you can:

  1. Group all the controls on a given "form" into a Panel or GroupBox, then show/hide the container control.

  2. Put all the controls into UserControls and have an instance of each UserControl on the main form. You can then show/hide the control.

I prefer the second method as it keeps the encapsulation tighter. Since you already have two forms, its easy to convert to user controls.