富文本框如何突出显示文本块而不选择

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

这里重要的是在没有使用richtextbox.select函数的情况下实现上述function,因为我所拥有的richtextbox正在定期更新,如果它在每次更新时调用select函数,用户将很难拖动文本而我不会我不希望这种情况发生。

我在编辑rtf的某个地方听到过一个解决方案,但我不完全确定如何做到这一点。 我很感激任何帮助。

编辑:刚刚意识到问题是winforms。 以下答案适用于WPF,而不是删除我会离开它,以防有人发现它有用。

使用TextRange(…)获取文本并应用背景,例如:

TextRange tr = new TextRange(position, nextPosition); var Br = new SolidColorBrush(Color.FromScRgb(alpha, 1f, 1f, 0f)); tr.ApplyPropertyValue(TextElement.BackgroundProperty, Br); 

但也许您应该研究一下您的更新机制并提出更好的解决方案。

这不使用richtextbox的Select()函数。 它只使用选择的start and end indexand updates the region with适当的colour and updates the region那些坐标中and updates the region

  // change the co-ordinates as per the selection in the run-time richTextBox1.Text = "Select some text"; richTextBox1.SelectionStart = 0; richTextBox1.SelectionLength = 4; richTextBox1.SelectionBackColor = Color.LightBlue; 

对于上面的代码, Sele将在Light Blue被选中。