简体   繁体   English

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

[英]How To Center Align the Title Bar text In Windows Form?

I am developing a Windows Form Application.我正在开发一个 Windows 窗体应用程序。 I want to Align the Text to Center or say to Right of Title Bar of Form.我想将文本与中心对齐或说到表单标题栏的右侧。 How can I do it ??我该怎么做 ??

It can be done with custom form - you will have to create your own title bar.可以使用自定义表单来完成 - 您必须创建自己的标题栏。 See V4Vendettas comment;见 V4Vendettas 评论;

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;但是,您必须添加 form.Refresh() 并在 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 += " ";
       tmpWidth += widthOfASpace;
    }

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

If it's a text that's inside a control (Like a label), you can edit the property named "TextAlign" to accomplish what you want inside Windows Form Designer.如果它是控件内的文本(如标签),则可以编辑名为“TextAlign”的属性以在 Windows 窗体设计器中完成所需的操作。

Or programmatically,或以编程方式,

Label.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;

If you're talking about aligning the text of the title bar, there is no way to do this through Winforms.如果您正在谈论对齐标题栏的文本,则无法通过 Winforms 执行此操作。 You will have to use something like this: http://www.codeproject.com/Articles/93959/WinForm-Extended你将不得不使用这样的东西: http : //www.codeproject.com/Articles/93959/WinForm-Extended

 Graphics g = this.CreateGraphics();
        double fw = this.Width; // form width
        double tw = g.MeasureString(this.Text.Trim(), this.Font).Width; \\ text width
        double rp = (fw - tw) / 2;
        int tt = Convert.ToInt32(rp); 
        string st = " ";
        st = st.PadRight(tt / 3);
        this.Text = st + this.Text.Trim();

Inside Windows Form Designer.在 Windows 窗体设计器中。 Make the changes like this.lable1.AutoSize = false ;进行这样的更改this.lable1.AutoSize = false ;

Then:然后:

this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM