C# 如何根据第一张表格设置第二张表格的位置?
我的项目中有Form1和Form2以及一个按钮。当我点击按钮时,将显示Form2。设置Form2在form1中心位置的命令是什么?将forms StartPosition属性设置为CenterParent。这样,它将始终在中心弹出。您需要使用第二个表单的实例。请参见My2表单项目的示例 表格一C# 如何根据第一张表格设置第二张表格的位置?,c#,C#,我的项目中有Form1和Form2以及一个按钮。当我点击按钮时,将显示Form2。设置Form2在form1中心位置的命令是什么?将forms StartPosition属性设置为CenterParent。这样,它将始终在中心弹出。您需要使用第二个表单的实例。请参见My2表单项目的示例 表格一 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
Form2 form2;
public Form1()
{
InitializeComponent();
form2 = new Form2(this);
}
private void button1_Click(object sender, EventArgs e)
{
form2.Show();
string results = form2.GetData();
}
}
}
表格二
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
Form1 form1;
public Form2(Form1 nform1)
{
InitializeComponent();
this.FormClosing += new FormClosingEventHandler(Form2_FormClosing);
form1 = nform1;
form1.Hide();
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
//stops form from closing
e.Cancel = true;
this.Hide();
}
public string GetData()
{
return "The quick brown fox jumped over the lazy dog";
}
}
}
您可以在打开位置时手动设置位置:
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.StartPosition = FormStartPosition.Manual;
f2.Load += delegate(object s2, EventArgs e2)
{
f2.Location = new Point(this.Bounds.Location.X + this.Bounds.Width / 2 - f2.Width / 2,
this.Bounds.Location.Y + this.Bounds.Height / 2 - f2.Height / 2);
};
f2.Show();
}
这里的关键是将设置为手动。
在我的系统上,将
StartPosition
设置为centerprist
并使用Show(this)
不会以“所有者”为中心。也许我的系统中有什么东西坏了……对我来说一直都是这样。你知道MDI表单吗?
?我不使用MDI表单,不仅仅是屏幕的中心,而是我想要form2 Form1的中心。抄袭了一些东西。中心父级是您想要的。这就是您想要使用的,不需要重新发明轮子。请参阅其他帖子的回复。投票被否决,因为您的答案中完全没有与位置相关的内容。作者:我的回复是您需要使用类的实例,我的示例正好说明了这一点。我没有具体说明如何传递设置位置的参数,但它类似于发布的代码。所有其他解决方案都是在我使用form类的实例之后使用的。@jdweng OP已经知道如何实例化表单,他想知道如何将表单居中。你确定OP知道如何实例化吗?这是不正确的,Bounds属性在Load事件激发之前是没有意义的。只有到那时,您才能知道窗口的真实大小,用户首选项和DPI重定比例都已应用。实际使用Load事件的少数原因之一。@HansPassant…正在通过按钮单击处理程序中的this
访问已打开的Form1的Bounds属性。我没有访问Form2的边界…只是使用了f2.Width
和f2.Height
,这应该是表单的设计宽度/高度…?当然,我在注释中出错了,问题出在f2.Width/Height上。在运行时,它将不是设计大小。用户覆盖是标题按钮和字体的大小,DPI重新缩放确保它们与设计大小完全不同。解决方法很简单,请使用Load事件。既然已经有CenterParent属性,为什么还要手动执行此操作?@ArthurRey,CenterParent可以很好地使用ShowDialog(),但不能使用Show()……或者我缺少什么?