首页 > 技术文章 > WinForm中使用自定义Tooltip控件

wyp1988 2018-11-02 16:29 原文

  • 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));
    • 限制宽度/每行字符数(自动换行)
      •  1         private const int maximumSingleLineTooltipLength = 120;
         2 
         3         private static string AddNewLinesForTooltip(string text)
         4         {
         5             if (text.Length < maximumSingleLineTooltipLength)
         6                 return text;
         7 
         8             StringBuilder sb = new StringBuilder();
         9 
        10             int currentLinePosition = 0;
        11             for (int textIndex = 0; textIndex < text.Length; textIndex++)
        12             {
        13                 sb.Append(text[textIndex]);
        14 
        15                 // if reach the original new line in the text
        16                 // just recount
        17                 if (text[textIndex].Equals(Environment.NewLine)
        18                     || (text[textIndex].Equals('\n') && textIndex >= 1 && text[textIndex - 1].Equals('\r')))
        19                 {
        20                     currentLinePosition = 0;
        21                     continue;
        22                 }
        23 
        24                 // If we have reached the target line length 
        25                 // and the nextcharacter is whitespace 
        26                 // and don't break \r\n
        27                 // then begin a new line.
        28                 if (currentLinePosition >= maximumSingleLineTooltipLength
        29                     && char.IsWhiteSpace(text[textIndex])
        30                     && !(text[textIndex].Equals('\r') && textIndex < text.Length && text[textIndex + 1].Equals('\n')))
        31                 {
        32                     sb.Append(Environment.NewLine);
        33                     currentLinePosition = 0;
        34                     continue;
        35                 }
        36 
        37                 // Append the next character.
        38                 if (textIndex < text.Length)
        39                 {
        40                     currentLinePosition++;
        41                 }
        42             }
        43 
        44             return sb.ToString();
        45         }
        View Code

         

推荐阅读