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。

相关推荐
overmind1 小时前
oeasy Python 115 列表弹栈用pop删除指定索引
开发语言·python
Never_Satisfied1 小时前
在c#中,使用windows自带功能将文件夹打包为ZIP
开发语言·windows·c#
hnxaoli2 小时前
win10程序(十六)通达信参数清洗器
开发语言·python·小程序·股票·炒股
电饭叔2 小时前
文本为 “ok”、前景色为白色、背景色为红色,且点击后触发 processOK 回调函数的 tkinter 按钮
开发语言·python
Never_Satisfied3 小时前
在c#中,string.replace会替换所有满足条件的子字符串,如何只替换一次
开发语言·c#
Demon_Hao4 小时前
JAVA快速对接三方支付通道标准模版
java·开发语言
xyq20245 小时前
C# 判断语句详解与应用
开发语言
野犬寒鸦5 小时前
深入解析HashMap核心机制(底层数据结构及扩容机制详解剖析)
java·服务器·开发语言·数据库·后端·面试
观无6 小时前
visionpro的dll导入
c#