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);
}
}
This is because you are not telling
f2who itsParentis.If this is an MDI application, then
f2should have itsMdiParentset tof1.If this is not an MDI application, then you need to call the
ShowDialogmethod usingf1as the parameter.Note that
CenterParentdoes not work correctly withShowsince there is no way to set theParent, so ifShowDialogis not appropriate, the manual approach is the only viable one.