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

如何扩展WinForms ToolTip文本的宽度尺寸?

解决WinForms ToolTip宽度自动扩展问题

现有代码的问题

  1. 文本获取逻辑错误:通过(sender as ToolTip).Tag获取关联控件不可靠,应使用e.AssociatedControl直接获取当前触发ToolTip的控件。
  2. 字体不统一:Popup事件用SystemFonts.SmallCaptionFont测量文本,Draw事件却用自定义的Tahoma 10字体,导致尺寸计算偏差。
  3. 文本格式设置错误:Draw事件中StringFormatFlags.NoWrap会强制文本不换行,无法利用设置的宽度实现自动换行,反而导致内容溢出。

有效解决方案

步骤1:配置ToolTip基础属性

确保ToolTip控件的OwnerDraw设为true,并绑定Popup和Draw事件。

步骤2:修正Popup事件代码

private void toolTip1_Popup(object sender, PopupEventArgs e)
{
    string tipText = toolTip1.GetToolTip(e.AssociatedControl);
    if (string.IsNullOrEmpty(tipText)) return;

    // 统一使用Draw事件中的字体测量文本尺寸
    using (Font tipFont = new Font("Tahoma", 10))
    {
        // 指定最大宽度(按需调整,示例为456),自动计算换行后的高度
        Size textSize = TextRenderer.MeasureText(
            tipText, 
            tipFont, 
            new Size(456, int.MaxValue), 
            TextFormatFlags.WordBreak);
        
        e.ToolTipSize = textSize;
    }
}

步骤3:修正Draw事件代码

private void toolTip1_Draw(object sender, DrawToolTipEventArgs e)
{
    // 保留系统默认的背景和边框绘制(也可自定义样式)
    e.DrawBackground();
    e.DrawBorder();

    using (StringFormat sf = new StringFormat())
    {
        sf.Alignment = StringAlignment.Near;
        sf.LineAlignment = StringAlignment.Top;
        sf.HotkeyPrefix = System.Drawing.Text.HotkeyPrefix.None;
        // 移除NoWrap,允许文本自动换行
        // sf.FormatFlags = StringFormatFlags.NoWrap;

        using (Font f = new Font("Tahoma", 10))
        {
            // 添加内边距,避免文本紧贴边框
            Rectangle textRect = new Rectangle(
                e.Bounds.X + 2, 
                e.Bounds.Y + 2, 
                e.Bounds.Width - 4, 
                e.Bounds.Height - 4);
            
            e.Graphics.DrawString(e.ToolTipText, f, SystemBrushes.ActiveCaptionText, textRect, sf);
        }
    }
}

关键说明

  • 字体统一:Popup和Draw事件必须使用相同字体,保证文本测量与绘制的尺寸匹配。
  • WordBreak标识:TextFormatFlags.WordBreak让TextRenderer.MeasureText自动计算换行后的高度。
  • 内边距调整:绘制文本时添加少量内边距,提升ToolTip的视觉舒适度。

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:46:07