0

I have three forms in C#, now when I want to show form2 I hide the main one and show the form and then when done working, hide the second form and show the main form again - I am doing this with the simple hide and show functions in winforms. Now the problem is every called form is placed on a different location on the screen, while I want all of them to stay on the same place. How to do it?

Gero Perov
  • 35
  • 1
  • 6

2 Answers2

2

Try setting the owner of the form when you call .Show()

You can also set the start position before you call show with .StartPosition = FormStartPosition.CenterParent

Or set the form.Location property after you call show

See here and here for more details

Community
  • 1
  • 1
Rich
  • 3,640
  • 3
  • 20
  • 24
1

You no doubt have a bug in your code, you are creating a new instance of the form instead of calling Show() again on the hidden form object. That's a bad kind of bug, it will make your program consume a lot of machine resources, ultimately it will crash when Windows refuses to allow your process to create more windows.

To make your scheme work, you have to write code that distinguishes between a closed form and a hidden one. Best way to do that is to explicitly keep track of its lifetime with the FormClosed event. Like this:

    private Form2 form2Instance;

    private void button1_Click(object sender, EventArgs e) {
        if (form2Instance == null) {
            // Doesn't exist yet, so create and show it
            form2Instance = new Form2();
            form2Instance.FormClosed += delegate { form2Instance = null; };
            form2Instance.Show();
        }
        else {
            // Already exists, unhide, restore and activate it
            form2Instance.WindowState = FormWindowState.Normal;
            form2Instance.Visible = true;
            form2Instance.BringToFront();
        }

    }
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536