C# 中控件richtextbox中某一行的条目内容高亮,未选中保持不变。当鼠标点击某一行的条目高亮,离开该条目就恢复默认颜色。
运行效果:
核心代码实现功能:
//高亮指定行的方法private void HighlightLine(RichTextBox rtb,int lineIndex,Color color){//恢复原来的颜色if(lastHighlightedLine!=-1&&lastHighlightedLine!=lineIndex){int oldStart = rtb.GetFirstCharIndexFromLine(lastHighlightedLine);int oldLength = GetLineLength(rtb, lastHighlightedLine);rtb.Select(oldStart, oldLength);rtb.SelectionColor = originalColor;//恢复默认颜色}int startIndex = rtb.GetFirstCharIndexFromLine(lineIndex);if(startIndex == -1)return;int nextLineStart = rtb.GetFirstCharIndexFromLine(lineIndex + 1);int length = (nextLineStart == -1) ? rtb.TextLength - startIndex : nextLineStart - startIndex;rtb.Select(startIndex, length);rtb.SelectionColor = color;rtb.Select(0, 0);//重置选中状态// 滚动到高亮行 rtb.ScrollToCaret();//更新状态lastHighlightedLine = lineIndex;originalColor = rtb.ForeColor;//假设默认颜色与控件一致}//辅助方法,获取行长度private int GetLineLength(RichTextBox rtb,int lineIndex){int start = rtb.GetFirstCharIndexFromLine(lineIndex);if (start == -1)return 0;int nextLineStart = rtb.GetFirstCharIndexFromLine(lineIndex + 1);return (nextLineStart == -1) ? rtb.TextLength - start : nextLineStart - start;}private void richTextBox_对位系统_MouseDown(object sender, MouseEventArgs e){//获取鼠标点击位置的字符索引int charIndex = richTextBox_对位系统.GetCharIndexFromPosition(e.Location);if (charIndex == -1)return;//计算点击位置所在的行号(注意:行号从0开始)int lineNumber = richTextBox_对位系统.GetLineFromCharIndex(charIndex);//高亮该行HighlightLine(richTextBox_对位系统, lineNumber, Color.LightBlue);}
关注知识代码AI。