C# 富文本框如何高亮显示文本块

C# 富文本框如何高亮显示文本块,c#,.net,winforms,richtextbox,C#,.net,Winforms,Richtextbox,我需要在RTB中突出显示文本的某一部分,而不是改变字体样式/颜色,而是使用特定颜色进行块选择。这类似于VisualStudio在调试模式下高亮显示一行的方式 我如何使用RTB实现这个特性,或者更确切地说,这是可能的吗?如果不可能,我想听听执行上述任务的另一种方法。我想您正在寻找 另一方面,如果您希望自己在RTB中执行此操作,则可以通过首先使用属性查找lineNumber来执行此操作。然后 //Select the line from it's number startIndex = richTe

我需要在RTB中突出显示文本的某一部分,而不是改变字体样式/颜色,而是使用特定颜色进行块选择。这类似于VisualStudio在调试模式下高亮显示一行的方式


我如何使用RTB实现这个特性,或者更确切地说,这是可能的吗?如果不可能,我想听听执行上述任务的另一种方法。

我想您正在寻找

另一方面,如果您希望自己在RTB中执行此操作,则可以通过首先使用属性查找
lineNumber
来执行此操作。然后

//Select the line from it's number
startIndex = richTextBox.GetFirstCharIndexFromLine(lineNumber);
richTextBox.Select(startIndex, length);

//Set the selected text fore and background color
richTextBox.SelectionColor = System.Drawing.Color.White;
richTextBox.SelectionBackColor= System.Drawing.Color.Blue;

是,您可以使用属性设置RichTextBox选择的背景色

int blockStart = 1; //arbitrary numbers to test
int blockLength = 15;
richTextBox1.SelectionStart = blockStart;
richTextBox1.SelectionLength = blockLength;
richTextBox1.SelectionBackColor = Color.Yellow;

在这里,我创建了CustomRichTextBox来实现这一点

这里解释了一个长场景的源代码。如果您感兴趣,那么您可以直接重用这个usercontrol,而不用担心太多问题

情景

源代码:


我想你在找我。另一方面,如果您希望自己在RTB中执行此操作,则可以通过首先使用属性查找
lineNumber
来执行此操作。然后//从其编号richTextBox中选择行。GetFirstCharIndexFromLine(行号);richTextBox.Select(开始索引,长度)//设置所选文本的前置色和背景色richTextBox.SelectionColor=System.Drawing.color.White;richTextBox.SelectionBackColor=System.Drawin的可能重复项是否忽略
GetFirstCharIndexFromLine()
返回值,而不是将其保存到
startIndex
变量中?