且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何中心对齐标题栏文本在Windows窗体?

更新时间:2023-12-06 08:20:58

可以使用自定义表单做 - 你必须创建自己的标题栏。见V4Vendettas评论;

It can be done with custom form - you will have to create your own title bar. See V4Vendettas comment;

其他方法(的链接) - 是创建自己的处理程序的形式调整大小并插入有followong代码。它将从文本的左侧大小加空格适量。然而,你将需要添加form.Refresh()和调用form.Load该方法;同时你的窗口会有...在任务栏的文本。

Other approach (link) - is to create your own handler for form resize and insert there followong code. It will add appropriate amount of spaces from the left size of text. However you will have to add form.Refresh() and call that method in form.Load; also your window will have "..." as a text in task bar.

private void UpdateTextPosition()
{
    Graphics g = this.CreateGraphics();
    Double startingPoint = (this.Width / 2) - (g.MeasureString(this.Text.Trim(), this.Font).Width / 2);
    Double widthOfASpace = g.MeasureString(" ", this.Font).Width;
    String tmp = " ";
    Double tmpWidth = 0;

    while ((tmpWidth + widthOfASpace) < startingPoint)
    {
       tmp += " ";
       mpWidth += widthOfASpace;
    }

    this.Text = tmp + this.Text.Trim();
}