在winform中的窗体中居中控件

Nen*_*vic 4 c# label center winforms

我正在学习 C#,作为书中练习的一部分,我必须将标签放在表单中。表格是否足够大并不重要。我在这里 - 在 stackoverflow - 以及其他一些地方找到了不同的解决方案,我将其缩小到两个。但看起来,尽管这些解决方案非常流行,但它们并没有产生相同的结果。

看起来像那个 方法 1

myLabel.Left = (this.ClientSize.Width - myLabel.Width) / 2;
myLabel.Top = (this.ClientSize.Height - myLabel.Height) / 2;
Run Code Online (Sandbox Code Playgroud)

将产生稍微向左居中并从中心向上偏移的标签,并且该 方法 2

myLabel2.Dock = DockStyle.Fill;
myLabel2.TextAlign = ContentAlignment.MiddleCenter;
Run Code Online (Sandbox Code Playgroud)

将使其在表格中间完美对齐。

现在,我的问题是为什么存在差异,或者换句话说,为什么方法 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!"));
    }
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*son 6

发生这种情况是因为您在将标签添加到表单的控件之前使用了标签的宽度。

但是,自动调整大小的标签的宽度是在将其添加到控件列表之后计算的。在此之前,如果您查看宽度,它将是一些固定的默认值,例如 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;
}
Run Code Online (Sandbox Code Playgroud)

  • +1 - 对我来说似乎合乎逻辑。基本的“将差异除以 2”逻辑是否也存在一些舍入问题? (2认同)