winform 窗体中顶部标题居中显示

在网上看了很多例子,都不能居中,都有或多或少的问题

自己根据网友的代码改编入下:

先确随便写一个标题的内容:

 string titleMsg =“Winfrom Title”

获取对Graphics对象的引用:

Graphics g = this.CreateGraphics();

根据Graphics对象来计算标题的开始居中位置:

 

Double startingPoint = (this.Width / 2) - (g.MeasureString(titleMsg, this.Font).Width / 2);

 

计算一个空字符所占像素长度:

Double widthOfASpace = g.MeasureString(" ", this.Font).Width;

定义一个空字符串来用作为标题之前做占位:

  String tmp = " ";

定义一个初始占位像素:

Double tmpWidth = 0;

循环遍历,将startingPoint之前的像素都用空字符代替:

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

最后将标题字符跟换:

 this.Text = tmp + titleMsg;

完整代码如下:

 1    private void SetTitleCenter()
 2    {
 3             string titleMsg = "Winfrom Title";
 4             Graphics g = this.CreateGraphics();
 5             Double startingPoint = (this.Width / 2) - (g.MeasureString(titleMsg, this.Font).Width / 2);
 6             Double widthOfASpace = g.MeasureString(" ", this.Font).Width;
 7             String tmp = " ";
 8             Double tmpWidth = 0;
 9 
10             while ((tmpWidth + widthOfASpace) < startingPoint)
11             {
12                 tmp += " ";
13                 tmpWidth += widthOfASpace;
14             }
15             this.Text = tmp + titleMsg;
16    }

 将上面SetTitleCenter()方法写在窗体构造方法中的InitializeComponent()方法之后即可

 

参考地址:

https://blog.csdn.net/weixin_44022374/article/details/105459718

 

posted @ 2021-01-19 09:41  随风去远方  阅读(3371)  评论(0编辑  收藏  举报
// 博客园添加鼠标粒子吸附特效