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。

相关推荐
yugi98783833 分钟前
基于遗传算法优化主动悬架模糊控制的Matlab实现
开发语言·matlab
我是苏苏40 分钟前
C#高级:使用ConcurrentQueue做一个简易进程内通信的消息队列
java·windows·c#
moxiaoran57531 小时前
Go语言的错误处理
开发语言·后端·golang
yugi9878382 小时前
MATLAB的多层感知器(MLP)与极限学习机(ELM)实现
开发语言·matlab
Never_Satisfied2 小时前
C#获取汉字拼音字母方法总结
开发语言·c#
zh_xuan2 小时前
kotlin 密封类
开发语言·kotlin
码小猿的CPP工坊3 小时前
C++软件开发之内存泄漏闭坑方法
开发语言·c++
Ethan-D3 小时前
#每日一题19 回溯 + 全排列思想
java·开发语言·python·算法·leetcode
满栀5853 小时前
分页插件制作
开发语言·前端·javascript·jquery
froginwe113 小时前
C 标准库 - <stdio.h>
开发语言