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

时间:2010-12-03 06:53:00

标签: c# winforms button tooltip

我在winform上有一个Button 在各种操作过程中按钮文本长度可能很大..

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

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

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

5 个答案:

答案 0 :(得分:13)

希望这段代码可以帮助你

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);
}

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

答案 1 :(得分:1)

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

如果它大于你必须添加按钮运行时的工具提示属性

不要忘记通过拖动工具箱

在项目中添加ToolTip控件

由于

答案 2 :(得分:1)

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

答案 3 :(得分:1)

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

“iiiiiiiiii”没有

那么宽

“wwwwwwwwww”。

您应该使用`Graphics class

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 );

答案 4 :(得分:0)

最佳实践是它

    /// <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);