如何解决 WinForm窗体标题字符数限制 导致的显示不全问题?

现在需要对窗体标题进行居中显示,通过在标题内容前增加空格的方式达到该目的。

实测是发现窗口标题的字符数量受到操作系统限制

网上查询的最大标题字符数是260个字符

实测最大字符数为587个

下面的代码可以勉强解决“由于最大字符数受到操作系统的限制导致最大化时显示不全”的问题

 1         string iniTitle = "";
 2         private void TitleCenterize()
 3         {
 4             this.MaximizedBounds = Screen.PrimaryScreen.WorkingArea;
 5             string titleMsg;
 6             if (this.Text.Length<=20)
 7             {
 8                 iniTitle = this.Text;
 9                 titleMsg = this.Text;
10             }
11             else
12             {
13                 titleMsg = iniTitle;
14             }
15             
16             Graphics g = this.CreateGraphics();
17             Double startingPoint = (this.Width / 2) - (g.MeasureString(titleMsg, this.Font).Width / 2);
18             Double widthOfASpace = g.MeasureString(" ", this.Font).Width;
19             String tmp = " ";
20             Double tmpWidth = 0;
21             int maxTitleLenght = 587;
22             if (startingPoint >= maxTitleLenght)
23             {
24                 startingPoint = maxTitleLenght;
25             }
26             while ((tmpWidth + widthOfASpace) < startingPoint)
27             {
28                tmp += " ";
29                tmpWidth += widthOfASpace;
30              }
31             this.Text = tmp + titleMsg;
32             int textLength = tmp.Length;
33         }

 

posted @ 2024-03-19 18:21  尼古拉-卡什  阅读(57)  评论(0编辑  收藏  举报