FormStartPosition.CenterParent does not work

kol picture kol · Dec 19, 2011 · Viewed 28.9k times · Source

In the following code, only the second method works for me (.NET 4.0). FormStartPosition.CenterParent does not center the child form over its parent. Why?

Source: this SO question

using System;
using System.Drawing;
using System.Windows.Forms;

class Program
{
  private static Form f1;

  public static void Main()
  {
    f1 = new Form() { Width = 640, Height = 480 };
    f1.MouseClick += f1_MouseClick; 
    Application.Run(f1);
  }

  static void f1_MouseClick(object sender, MouseEventArgs e)
  {
    Form f2 = new Form() { Width = 400, Height = 300 };
    switch (e.Button)
    {
      case MouseButtons.Left:
      {
        // 1st method
        f2.StartPosition = FormStartPosition.CenterParent;
        break;
      }
      case MouseButtons.Right:
      {
        // 2nd method
        f2.StartPosition = FormStartPosition.Manual;
        f2.Location = new Point(
          f1.Location.X + (f1.Width - f2.Width) / 2, 
          f1.Location.Y + (f1.Height - f2.Height) / 2
        );
        break;
      }
    }
    f2.Show(f1); 
  }
}

Answer

competent_tech picture competent_tech · Dec 19, 2011

This is because you are not telling f2 who its Parent is.

If this is an MDI application, then f2 should have its MdiParent set to f1.

Form f2 = new Form() { Width = 400, Height = 300 };
f2.StartPosition = FormStartPosition.CenterParent;
f2.MdiParent = f1;
f2.Show();

If this is not an MDI application, then you need to call the ShowDialog method using f1 as the parameter.

Form f2 = new Form() { Width = 400, Height = 300 };
f2.StartPosition = FormStartPosition.CenterParent;
f2.ShowDialog(f1);

Note that CenterParent does not work correctly with Show since there is no way to set the Parent, so if ShowDialog is not appropriate, the manual approach is the only viable one.