Show a child form in the centre of Parent form in

2019-01-06 14:25发布

I create a new form and call from the parent form as follows:

loginForm = new SubLogin();   
loginForm.Show();

I need to display the child form at the centre of the parent. So,in the child form load I do the foll:`

Point p = new Point(this.ParentForm.Width / 2 - this.Width / 2, this.ParentForm.Height / 2 - this.Height / 2);
this.Location = p;

But this is throwing error as parent form is null. I tried setting the Parent property as well, but didn't help. Any inputs on this?

标签: c# winforms
16条回答
来,给爷笑一个
2楼-- · 2019-01-06 14:43

Try:

loginForm.StartPosition = FormStartPosition.CenterParent;
loginForm.ShowDialog(this);

Of course the child for will now be a blocking form (dialog) of the parent window, if that isn't desired then just replace ShowDialog with Show..

loginForm.Show(this);

You will still need to specify the StartPosition though.

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-06 14:43

You need this:

Replace Me with this.parent, but you need to set parent before you show that form.

  Private Sub ÜberToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ÜberToolStripMenuItem.Click

        'About.StartPosition = FormStartPosition.Manual ' !!!!!
        About.Location = New Point(Me.Location.X + Me.Width / 2 - About.Width / 2, Me.Location.Y + Me.Height / 2 - About.Height / 2)
        About.Show()
    End Sub
查看更多
4楼-- · 2019-01-06 14:43

On the SubLogin Form I would expose a SetLocation method so that you can set it from your parent form:

public class SubLogin : Form
{
   public void SetLocation(Point p)
   {
      this.Location = p;
   }
} 

Then, from your main form:

loginForm = new SubLogin();   
Point p = //do math to get point
loginForm.SetLocation(p);
loginForm.Show();
查看更多
Explosion°爆炸
5楼-- · 2019-01-06 14:44

The setting of parent does not work for me unless I use form.ShowDialog();.

When using form.Show(); or form.Show(this); nothing worked until I used, this.CenterToParent();. I just put that in the Load method of the form. All is good.

Start position to the center of parent was set and does work when using the blocking showdialog.

查看更多
可以哭但决不认输i
6楼-- · 2019-01-06 14:46

When launching a form inside an MDIForm form you will need to use .CenterScreen instead of .CenterParent.

FrmLogin f = new FrmLogin();
f.MdiParent = this;
f.StartPosition = FormStartPosition.CenterScreen;
f.Show();
查看更多
看我几分像从前
7楼-- · 2019-01-06 14:46

The parent probably isn't yet set when you are trying to access it.

Try this:

loginForm = new SubLogin();
loginForm.Show(this);
loginForm.CenterToParent()
查看更多
登录 后发表回答