WinForms工具提示中的文本长度

时间:2011-08-16 09:27:40

标签: winforms tooltip

如何在WinForms工具提示中设置文本的最大长度? 我有一个大约300个字符的字符串,但我的工具提示只显示其中的264个......

迎接,

尔根

3 个答案:

答案 0 :(得分:3)

你可以在你的ToolTip字符串中添加 NewLine 几次,这样就不会在屏幕上一直显示。

此代码中的字符串长度为434个字符。

: - )

只需运行此代码即可试用:>>

Imports System.Environment

Public Class Form1

    Friend WithEvents myToolTip As New ToolTip

    Private Sub Form1_MouseHover(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.MouseHover

        Dim someText As String = _
        "Hello World!! Hi everyone!! Good day, good evening or goodnight, wherever you are in the world!!  :-)   :-D" & NewLine & _
        "Hello World!! Hi everyone!! Good day, good evening or goodnight, wherever you are in the world!!  :-)   :-D" & NewLine & _
        "Hello World!! Hi everyone!! Good day, good evening or goodnight, wherever you are in the world!!  :-)   :-D" & NewLine & _
        "Hello World!! Hi everyone!! Good day, good evening or goodnight, wherever you are in the world!!  :-)   :-D"

        Me.Text = someText.Length.ToString
        myToolTip.Show(someText, Me, 5000)

    End Sub

End Class

答案 1 :(得分:0)

我遇到了同样的问题(碰巧是DataGridView单元),并且默认的工具提示文本(即单元的文本内容)确实被截断了。

对我来说,当我显式设置工具提示文本时,它开始正常工作(我看到的所有答案都这样做了)。我认为微妙的是,默认ToolTip文本使用相同的单元格内容,只有默认处理程序会像原始问题中所述截断它。通过覆盖事件并设置ToolTip文本(即使它是完全相同的单元格文本!),默认长度限制似乎也消失了。

protected override void OnCellToolTipTextNeeded(DataGridViewCellToolTipTextNeededEventArgs e)
{
    if((e.RowIndex >= 0) && (e.ColumnIndex >= 0))
    {
        // By setting this explicitly we can make the ToolTip length
        // longer even though the content is exactly the same.
        e.ToolTipText = this[e.ColumnIndex, e.RowIndex].Value.ToString();
    }
    base.OnCellToolTipTextNeeded(e);
}

其他控件当然会触发不同的事件,但是应该坚持认为,如果您自己将文本放在工具提示上,则可以避免任何默认ToolTip发生的截断。

答案 2 :(得分:0)

我知道这是一个古老的问题,我不确定当时是否存在以下功能,但是对于那些正在搜索此功能的人来说,我注意到如果工具提示文本很长,则可能根本无法显示,经过一番尝试,发现这样做有帮助:

// 999 = just an arbitrary number to test for possible very long text, may have to fiddle with that (maybe screen width) !
// 456 = also arbitrary, change to your liking !
// tooltip.GetToolTip((sender as ToolTip).Tag as Control) is because I have multiple controls using the same Tooltip, so I set the Tooltip.Tag to the control that will call Tooltip.Show(...). If you have 1 tooltip per control than just replace it with the control in question.
tooltip.Popup += (sender, e) =>
{
    if (e.ToolTipSize.Width > 999)
    {
        Size s = TextRenderer.MeasureText(tooltip.GetToolTip((sender as ToolTip).Tag as Control), SystemFonts.SmallCaptionFont);
        e.ToolTipSize = new Size(456, s.Height * 3); // * 3 turned out to work for SystemFonts.SmallCaptionFont
    }
};