调用Form.Show()时设置窗体的位置

我试图通过.Show()调用时设置窗体的位置。 问题是,因为我使用.Show而不是.ShowDialog StartPosition值不起作用。 我不能使用.Showdialog因为我希望程序在显示窗体的同时在后台工作。

当我创build表单时,我将它的位置设置为固定值:

 using (ConnectingForm CF = new ConnectingForm()) { CF.Show(); CF.Location = new Point(this.ClientSize.Width / 2, this.ClientSize.Height / 2); } 

但是当我运行代码时,每次启动它时,表单都会置于不同的位置。

任何解决scheme (该位置是从来没有设置其他地方我的代码)

StartPosition应该与Form.Show一起正常工作。 尝试:

 ConnectingForm CF = new ConnectingForm(); CF.StartPosition = FormStartPosition.CenterParent; CF.Show(this); 

如果您想手动放置表单,如您所示,也可以这样做,但仍需要将StartPosition属性设置为Manual

 ConnectingForm CF = new ConnectingForm(); CF.StartPosition = FormStartPosition.Manual; CF.Location = new Point(this.ClientSize.Width / 2, this.ClientSize.Height / 2); CF.Show(); 

在旁注中,您不应该使用Form.Show using语句。 using将调用表单,这是不希望的,因为表单的生命周期比这个代码块更长。

从其他线程的一些帮助,我找到了一个工作解决方案:

  using (ConnectingForm CF = new ConnectingForm()) { CF.StartPosition = FormStartPosition.Manual; CF.Show(this); ...... } 

在新窗体的加载事件中:

  private void ConnectingForm_Load(object sender, EventArgs e) { this.Location = this.Owner.Location; this.Left += this.Owner.ClientSize.Width / 2 - this.Width / 2; this.Top += this.Owner.ClientSize.Height / 2 - this.Height / 2; } 

(我不是专家,所以请纠正我,如果我错了)下面是我如何解释问题和解决方案:从一开始的问题是,第一个窗体(MainForm)启动位置设置为Windows默认位置,当你启动表单。 当我然后调用新的窗体(连接窗体)时,它的位置不是相对于父窗口的位置,而是位置(0,0)(屏幕左上角)。 所以我看到的是MainForm的位置在变化,这看起来就像连接形式的位置正在移动。 所以这个问题的解决方案基本上是先将新表单的位置设置到主表单的位置。 之后,我可以将该位置设置为MainForm的中心。

TL; DR新表单的位置与父表单的位置不相关,但是我猜测的固定位置是(0,0)

为了方便起见,我把MainForm的Startup Position改为了固定的。 我还添加了一个事件,以确保新表单位置始终是MainForm的中心。

  private void Location_Changed(object sender, EventArgs e) { this.Location = this.Owner.Location; this.Left += this.Owner.ClientSize.Width / 2 - this.Width / 2; this.Top += this.Owner.ClientSize.Height / 2 - this.Height / 2; } private void ConnectingForm_Load(object sender, EventArgs e) { this.Owner.LocationChanged += new EventHandler(this.Location_Changed); this.Location = this.Owner.Location; this.Left += this.Owner.ClientSize.Width / 2 - this.Width / 2; this.Top += this.Owner.ClientSize.Height / 2 - this.Height / 2; } 

希望这会帮助其他同样的问题!