c# - 在 winform 的窗体中居中控件

标签 c# winforms label center

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

看起来是这样的 方法一

myLabel.Left = (this.ClientSize.Width - myLabel.Width) / 2;
myLabel.Top = (this.ClientSize.Height - myLabel.Height) / 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;
}

关于c# - 在 winform 的窗体中居中控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16278908/

相关文章:

JavaFX 设置数组中的标签文本

c# - 如何使用正则表达式进行不区分大小写的字符串替换?

c# - 如何使用C#修改WMV视频元数据?

c# - 导致内存不足异常的大字符串数组 (C#)

c# - DataGridView 设置行高不起作用

c# - 在窗口关闭时运行 Windows 窗体线程

c# - 并行执行多对并发任务

c# - 表单焦点问题

java - 用颜色归档标签

ios - 无法在 XCode 6.1.1 中更改字体