Rob*_*bin 14 .net c# windows visual-studio-2012
我正在尝试在调用时设置表单的位置.Show().问题是,因为我使用.Show而不是.ShowDialogStartPosition值不起作用.我不能使用.Showdialog因为我希望程序在显示表单时在后台工作.
当我创建表单时,我将其位置设置为固定值:
using (ConnectingForm CF = new ConnectingForm())
{
CF.Show();
CF.Location = new Point(this.ClientSize.Width / 2, this.ClientSize.Height / 2);
}
Run Code Online (Sandbox Code Playgroud)
但是当我运行代码时,每次启动时,表单都会将其置于不同的位置.
有解决方案吗 (我的代码永远不会在其他地方设置该位置)
Ree*_*sey 25
StartPosition应该可以正常工作Form.Show.尝试:
ConnectingForm CF = new ConnectingForm();
CF.StartPosition = FormStartPosition.CenterParent;
CF.Show(this);
Run Code Online (Sandbox Code Playgroud)
如果您想手动放置表单,如您所示,也可以这样做,但仍需要将StartPosition属性设置为Manual:
ConnectingForm CF = new ConnectingForm();
CF.StartPosition = FormStartPosition.Manual;
CF.Location = new Point(this.ClientSize.Width / 2, this.ClientSize.Height / 2);
CF.Show();
Run Code Online (Sandbox Code Playgroud)
另外,您不应该使用using声明Form.Show. using将调用Dispose表单,这是不希望的,因为表单的生命周期比这段代码长.
在其他线程的帮助下,我找到了一个可行的解决方案:
using (ConnectingForm CF = new ConnectingForm())
{
CF.StartPosition = FormStartPosition.Manual;
CF.Show(this);
......
}
Run Code Online (Sandbox Code Playgroud)
在新表单的加载事件:
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;
}
Run Code Online (Sandbox Code Playgroud)
(我不是专家,所以请纠正我,如果我错了)以下是我如何解释问题和解决方案:从一开始的问题是第一个窗体的(MainForm)启动位置设置为Windows默认位置,这是变化的当你启动表格时.当我调用新表单(连接表单)时,它的位置与其父级的位置无关,而是位置(0,0)(屏幕的顶部左侧角).所以我看到的是MainForms的位置变化,这使得它看起来像连接表的位置正在移动.因此,解决此问题的方法基本上是首先将新表单的位置设置为主表单的位置.之后,我能够将位置设置为MainForm的中心.
TL; DR新表单的位置不是相对于父表单的位置,而是相对于我猜的固定位置是(0,0)
为了方便起见,我将MainForm的启动位置更改为固定位置.我还添加了一个事件,以确保新表单位置始终是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;
}
Run Code Online (Sandbox Code Playgroud)
希望这会帮助其他人解决同样的问题!
| 归档时间: |
|
| 查看次数: |
32176 次 |
| 最近记录: |