C# winforms中窗体内的控件居中
我正在学习C#,作为本书练习的一部分,我必须将标签放在表格的中心。不管表单是否足够大。我在这里——在stackoverflow上——以及在其他一些地方发现了不同的解决方案,我将其缩小为两种。但看起来,尽管这些解决方案相当流行,但它们并没有产生相同的结果 看起来是这样的 方法1C# winforms中窗体内的控件居中,c#,winforms,label,center,C#,Winforms,Label,Center,我正在学习C#,作为本书练习的一部分,我必须将标签放在表格的中心。不管表单是否足够大。我在这里——在stackoverflow上——以及在其他一些地方发现了不同的解决方案,我将其缩小为两种。但看起来,尽管这些解决方案相当流行,但它们并没有产生相同的结果 看起来是这样的 方法1 myLabel.Left = (this.ClientSize.Width - myLabel.Width) / 2; myLabel.Top = (this.ClientSize.Height - myLabel.Hei
myLabel.Left = (this.ClientSize.Width - myLabel.Width) / 2;
myLabel.Top = (this.ClientSize.Height - myLabel.Height) / 2;
将产生标签稍微居中左侧,并从中心向上偏移
方法2
myLabel2.Dock = DockStyle.Fill;
myLabel2.TextAlign = ContentAlignment.MiddleCenter;
将使其在形状中间完全对齐
现在,我的问题是为什么会有差异,或者换句话说,为什么在方法1中会有左侧向上偏移
整个代码如下所示:
//Exercise 16.1
//-------------------
using System.Drawing;
using System.Windows.Forms;
public class frmApp : Form
{
public frmApp(string str)
{
InitializeComponent(str);
}
private void InitializeComponent(string str)
{
this.BackColor = Color.LightGray;
this.Text = str;
//this.FormBorderStyle = FormBorderStyle.Sizable;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.StartPosition = FormStartPosition.CenterScreen;
Label myLabel = new Label();
myLabel.Text = str;
myLabel.ForeColor = Color.Red;
myLabel.AutoSize = true;
myLabel.Left = (this.ClientSize.Width - myLabel.Width) / 2;
myLabel.Top = (this.ClientSize.Height - myLabel.Height) / 2;
Label myLabel2 = new Label();
myLabel2.Text = str;
myLabel2.ForeColor = Color.Blue;
myLabel2.AutoSize = false;
myLabel2.Dock = DockStyle.Fill;
myLabel2.TextAlign = ContentAlignment.MiddleCenter;
this.Controls.Add(myLabel);
this.Controls.Add(myLabel2);
}
public static void Main()
{
Application.Run(new frmApp("Hello World!"));
}
}
这是因为在将标签添加到窗体控件之前,正在使用标签的宽度 但是,自动调整大小的标签的宽度是在添加到控件列表后计算的。在此之前,如果您查看宽度,它将是一些固定的默认值,例如100 您可以通过重新排列代码来修复它,以便在将标签添加到表单控件后调整标签的位置
private void InitializeComponent(string str)
{
this.BackColor = Color.LightGray;
this.Text = str;
//this.FormBorderStyle = FormBorderStyle.Sizable;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.StartPosition = FormStartPosition.CenterScreen;
Label myLabel = new Label();
myLabel.Text = str;
myLabel.ForeColor = Color.Red;
myLabel.AutoSize = true;
Label myLabel2 = new Label();
myLabel2.Text = str;
myLabel2.ForeColor = Color.Blue;
myLabel2.AutoSize = false;
myLabel2.Dock = DockStyle.Fill;
myLabel2.TextAlign = ContentAlignment.MiddleCenter;
this.Controls.Add(myLabel);
this.Controls.Add(myLabel2);
myLabel.Left = (this.ClientSize.Width - myLabel.Width) / 2;
myLabel.Top = (this.ClientSize.Height - myLabel.Height) / 2;
}
+1-在我看来似乎合乎逻辑。基本的
除以2
逻辑是否也会存在一些舍入问题?@MichaelPerrenoud我认为居中计算应该足够接近,但可能会超出1像素。是的,你是对的,最大值约为1像素,因此可能不明显。实际上,即使按照Matthew Watson建议的方式重新排列代码,这些方法之间仍然有很小的偏移,就像我前面描述的那样。但是,当我改变这个时。FormBorderStyle=FormBorderStyle.FixedSingle;到this.FormBorderStyle=FormBorderStyle.sizeable;然后,两种方法的结果都是正确和相同的。