C# 实战_RichTextBox选中某一行条目高亮,离开恢复

C# 中控件richtextbox中某一行的条目内容高亮,未选中保持不变。当鼠标点击某一行的条目高亮,离开该条目就恢复默认颜色。

运行效果:

核心代码实现功能:

csharp 复制代码
//高亮指定行的方法
        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。

相关推荐
wt_cs2 分钟前
身份证实名认证接口数字时代的信任基石-node.js实名认证集成
开发语言·node.js·php
爱编程的鱼20 分钟前
C# 结构(Struct)
开发语言·人工智能·算法·c#
只可远观32 分钟前
Flutter Dart 循环语句 for while do..while break、continue
开发语言·javascript·ecmascript
是阿根1 小时前
unity使用iTextSharp生成PDF文件
unity·c#·游戏引擎
吴_知遇1 小时前
【华为OD机试真题】428、连续字母长度 | 机试真题+思路参考+代码解析(E卷)(C++)
开发语言·c++·华为od
basketball6162 小时前
Python torchvision.transforms 下常用图像处理方法
开发语言·图像处理·python
ABAP 成2 小时前
.NET Framework 4.0可用EXCEL导入至DataTable
c#
宁酱醇2 小时前
各种各样的bug合集
开发语言·笔记·python·gitlab·bug
啊吧怪不啊吧2 小时前
Linux常见指令介绍下(入门级)
linux·开发语言·centos
谷晓光2 小时前
Python 中 `r` 前缀:字符串处理的“防转义利器”
开发语言·python