WinForm中使用自定义Tooltip控件

时间:2023-01-22 15:18:58
  • private ToolTip tooltipCtr;
  • 构造函数中:
    • 隐藏默认的Tooltip:this.ShowCellToolTips = false;
    • this.tooltipCtr = new ToolTip();
    • 设置停留时间(还有许多其他时间设置):this.tooltipCtr.AutoPopDelay = 1000 * 60;
    • 在CellMouseEnterHandler等事件中设置数据,在鼠标处设置文本:tooltipCtr.Show(HttpUtility.HtmlDecode(((BasicData)this.Rows[rowIndex].DataBoundItem).VarDescLong), this, PointToClient(MousePosition));
    • 限制宽度/每行字符数(自动换行)
      •          private const int maximumSingleLineTooltipLength = ;
        
                 private static string AddNewLinesForTooltip(string text)
        {
        if (text.Length < maximumSingleLineTooltipLength)
        return text; StringBuilder sb = new StringBuilder(); int currentLinePosition = ;
        for (int textIndex = ; textIndex < text.Length; textIndex++)
        {
        sb.Append(text[textIndex]); // if reach the original new line in the text
        // just recount
        if (text[textIndex].Equals(Environment.NewLine)
        || (text[textIndex].Equals('\n') && textIndex >= && text[textIndex - ].Equals('\r')))
        {
        currentLinePosition = ;
        continue;
        } // If we have reached the target line length
        // and the nextcharacter is whitespace
        // and don't break \r\n
        // then begin a new line.
        if (currentLinePosition >= maximumSingleLineTooltipLength
        && char.IsWhiteSpace(text[textIndex])
        && !(text[textIndex].Equals('\r') && textIndex < text.Length && text[textIndex + ].Equals('\n')))
        {
        sb.Append(Environment.NewLine);
        currentLinePosition = ;
        continue;
        } // Append the next character.
        if (textIndex < text.Length)
        {
        currentLinePosition++;
        }
        } return sb.ToString();
        }