开发者

Show tooltip for a button when text is too long

I have a Button on the winform Button text length might very during various operations..

I don't want to vary the butt开发者_运维技巧on size(So I have set "Autosize" property to false)

How do I show tooltip(of complete button Text) on mouse hover whenever Button Text is getting cut?

Please Note that I don't want tooltip always..... I want it only when button text is getting cut


Hope this code will helps you

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

You must write those code in button mousehover event


I don't think the answers so far are quite correct - the length of the rendered string (and this is what you need when you also take your button's dimensions into account) may vary based on the font and also characters you use. Using a proportional font such as Microsoft Sans Serif will return different dimensions for strings containing the same number of characters when these characters differ, e.g.:

"iiiiiiiiii" is not as wide as

"wwwwwwwwww".

You should use the MeasureString method of the `Graphics class

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


I think you have to manually check length of text on button with size of button

and if it bigger than you have to add tooltip property of button runtime

Don't forget to add ToolTip control in your project by dragging from toolbox

Thanks


Alternative : use AutoElipsis property of the button to True.


The best practice is it

    /// <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)
        {
        }
    }

Can be called so ...

 ShowTextToolTip(MyControlTextBox,ToolTipIcon.None);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜