You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ToolStripLabel长文本显示异常,如何判断文本是否实际显示?

ToolStripLabel文本显示不全的判断问题

我用ToolStripLabel显示文本消息,文本过长时,除非放大窗体,否则无法完整显示,这是WinForms的已知问题。

我原本想通过获取文本尺寸(结合Font属性)和ToolStripLabel实际尺寸对比来判断,但尝试后发现即便文本宽度小于控件宽度,文本还是显示不全,怀疑是控件的边框等额外因素导致。

补充的测试代码

我尝试用以下代码获取文本渲染尺寸:

strTextToDisplayInToolStripLabel = "Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt"

Dim fakeImage As Image = New Bitmap(1, 1)
Dim graphics As Graphics = Graphics.FromImage(fakeImage)
Dim size As SizeF = graphics.MeasureString(strTextToDisplayInToolStripLabel, Me.MenuStripMain.Items("MyToolStripLabel").Font)

Debug.Print("String To Display Lenght: " & strTextToDisplayInToolStripLabel.Length.ToString)
Debug.Print("Text Size Width: " & size.Width.ToString)
Debug.Print("TSMI Size Width: " & Me.MenuStripMain.Items("tsmiMessage").Size.Width.ToString)

输出结果

String To Display Lenght: 87
Text Size Width: 490,97186
TSMI Size Width: 494

请问有没有办法判断ToolStripLabel的文本是否已经实际完整显示?


解决方案

  1. 修正文本尺寸测量逻辑
    Graphics.MeasureString未考虑ToolStripLabel的内部边距和布局规则,改用TextRenderer.MeasureText结合控件DisplayRectangle(去除边框、内边距后的实际绘制区域)计算,更贴近WinForms的文本渲染逻辑:
Dim toolStripLabel = CType(Me.MenuStripMain.Items("tsmiMessage"), ToolStripLabel)
Dim textSize = TextRenderer.MeasureText(strTextToDisplayInToolStripLabel, toolStripLabel.Font, 
    New Size(toolStripLabel.DisplayRectangle.Width, Int32.MaxValue), 
    TextFormatFlags.SingleLine Or TextFormatFlags.NoPrefix)

' 判断文本是否超出可用宽度
Dim isTextTruncated = textSize.Width > toolStripLabel.DisplayRectangle.Width
  1. 通过反射判断内部截断状态
    ToolStripLabel未公开直接判断文本截断的属性,但可通过反射获取内部的_textRectangle字段,对比文本所需宽度和该矩形宽度:
Dim toolStripLabel = CType(Me.MenuStripMain.Items("tsmiMessage"), ToolStripLabel)
Dim textRectField = GetType(ToolStripLabel).GetField("_textRectangle", BindingFlags.NonPublic Or BindingFlags.Instance)
If textRectField IsNot Nothing Then
    Dim textRect = DirectCast(textRectField.GetValue(toolStripLabel), Rectangle)
    Dim textSize = TextRenderer.MeasureText(strTextToDisplayInToolStripLabel, toolStripLabel.Font)
    Dim isTruncated = textSize.Width > textRect.Width
    Debug.Print("文本是否截断: " & isTruncated.ToString())
End If

注:反射依赖控件内部实现,可能随.NET版本变更失效。

  1. 直接调整控件宽度避免截断
    如果核心需求是让文本完整显示,可在设置文本后手动调整控件宽度:
Dim toolStripLabel = CType(Me.MenuStripMain.Items("tsmiMessage"), ToolStripLabel)
toolStripLabel.Text = strTextToDisplayInToolStripLabel
Dim textSize = TextRenderer.MeasureText(toolStripLabel.Text, toolStripLabel.Font)
toolStripLabel.Size = New Size(textSize.Width + 4, toolStripLabel.Size.Height) ' +4预留少量边距

内容的提问来源于stack exchange,提问作者8oris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 13:03:18