繁体   English   中英

文本太长时显示按钮的工具提示

[英]Show tooltip for a button when text is too long

我在winform上有一个Button按钮文本长度可能在各种操作期间。

我不想改变按钮大小(所以我将“Autosize”属性设置为false)

按钮文本被剪切时,如何在鼠标悬停时显示工具提示(完整按钮文本)?

请注意,我不希望工具提示总是.....我只想在按钮文字被剪切时才想要它

希望这段代码能帮到你

if (button1.Text.Length > Your button text length to be checked)
{
    System.Windows.Forms.ToolTip ToolTip1 = new System.Windows.Forms.ToolTip();
    ToolTip1.SetToolTip(this.button1, this.button1.Text);
}

您必须在按钮鼠标悬停事件中编写这些代码

我不认为到目前为止的答案是非常正确的 - 渲染字符串的长度(这也是你考虑按钮尺寸时所需要的)可能会根据字体和你使用的字符而有所不同。 使用比例字体(如Microsoft Sans Serif将为这些字符不同时包含相同字符数的字符串返回不同的维度,例如:

“iiiiiiiiii”并不像

“wwwwwwwwww”。

您应该使用`Graphics类的MeasureString方法

Graphics grfx = Graphics.FromImage( new Bitmap( 1, 1 ) );

// Set a proportional font
button1.Font = new Font( "Microsoft Sans Serif", 8.25f, FontStyle.Regular );
SizeF bounds = grfx.MeasureString(
    button1.Text,
    button1.Font,
    new PointF( 0, 0 ),
    new StringFormat( StringFormatFlags.MeasureTrailingSpaces ) );
MessageBox.Show( "Text dimensions: " + bounds.Width + "x" + bounds.Height );

// Set a non-proportional font
button1.Font = new Font( "Courier New", 8.25f, FontStyle.Regular );
bounds = grfx.MeasureString(
    button1.Text,
    button1.Font,
    new PointF( 0, 0 ),
    new StringFormat( StringFormatFlags.MeasureTrailingSpaces ) );
MessageBox.Show( "Text dimensions: " + bounds.Width + "x" + bounds.Height );

替代方法:使用按钮的AutoElipsis属性为True。

我认为您必须手动检查按钮大小的按钮上的文本长度

如果它大于你必须添加按钮运行时的tooltip属性

不要忘记通过从工具箱拖动来在项目中添加ToolTip控件

谢谢

最好的做法是它

    /// <summary>
    ///     Exibe texto do controle num tipo ToolTip do winform
    /// </summary>
    /// <param name="controle">Controle</param>
    /// <param name="icon"></param>
    public static void ShowTextToolTip(Control controle, ToolTipIcon icon)
    {
        try
        {
            var tooltip = new ToolTip();
            tooltip.ToolTipIcon = icon;

            controle.MouseHover += (k, args) => { tooltip.SetToolTip(controle, controle.Text); };
        }
        catch (Exception)
        {
        }
    }

可以这么称呼......

 ShowTextToolTip(MyControlTextBox,ToolTipIcon.None);

暂无
暂无

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

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