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。

相关推荐
烟烟Abandon43 分钟前
FFmpeg开发基础之 C 语言 :再论指针(讲透指针)
c语言·开发语言·ffmpeg
阿俊-全栈开发4 小时前
扩展设计解析:LikeShop Go 版商城营销活动的插件化扩展设计思路
开发语言·微服务·golang·likeshop·likeshop源码
干啥啥不行,bug第一名4 小时前
EAFNOSUPPORT、EPROTOTYPE、EOPNOTSUPP:socket 的三层参数没有对齐
开发语言·php
我要见SA姐15 小时前
用生活化类比当钥匙,一键打开 C++ 入门大门
java·开发语言·c++
1024奇点5 小时前
第四篇 第 03 课
开发语言·ide·后端
大彼方..6 小时前
CSDN-02-开发环境介绍与安装
c语言·开发语言·stm32
BK贝壳6 小时前
初始化一亿个全 True 或全 False:bool-hybrid-array 的 TruesArray/FalsesArray 占位构造本机实测
开发语言·数据结构·python·性能优化·numpy
L-影7 小时前
HashMap详解-上篇
java·开发语言·spring·hashmap
郝学胜-神的一滴7 小时前
Effective STL 条款 17:用 swap 技巧去掉多余容量
c语言·开发语言·数据结构·c++·算法·rpc
摇滚侠7 小时前
《On Java 中文版 基础卷》阅读笔记 集合 24
java·开发语言·笔记