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。

相关推荐
会周易的程序员19 分钟前
给 PLC 写一个字节码虚拟机:STVM 虚拟机架构设计
开发语言·c++·虚拟机·软plc·iec61131·stvm
机器视觉知识推荐、就业指导24 分钟前
为什么老说“纯 Qt 没啥就业市场”?
开发语言·qt
telepan25 分钟前
Qt 开发避坑与性能指南:如何优雅、安全地定义全局常量字符串?
开发语言·qt
m0_6952514941 分钟前
Qt MaintenanceTool 使用国内镜像加速下载(超详细教程)
开发语言·qt
大衛說2 小时前
《Python 从入门到精通》系列总览与学习路线
开发语言·python·学习
可乐鸡翅yeah_3 小时前
hls.js 内存泄漏实战排查,直播 M3U8 长时间播放异常定位方案
开发语言·javascript·python·django·ecmascript·m3u8·m3u8在线
2601_962203513 小时前
Java进阶07集合(续)
java·开发语言
郑州光合科技余经理4 小时前
本地生活服务系统:模块边界与结算字段怎么拆
java·开发语言·前端·后端·系统架构·uni-app·php
来了就未晚4 小时前
Python基础 学习代码存储与命名规范
开发语言·python·学习
布莱克6054 小时前
数组详解:定义、作用、应用场景及与链表的区别(C/C++ 代码讲解)
c语言·开发语言·c++·数组