RichTextBox SelectionStart偏移量与换行符

时间:2013-10-10 10:22:17

标签: c# winforms richtextbox

我正在使用RichTextBox作为彩色文本。我们假设我想为文本的不同部分使用不同的颜色。到目前为止,此工作正常。

我目前遇到RichTextBox的SelectionStart属性问题。我已经将一些文本设置为RichTextBox的Text属性。如果文本包含\r\n\r\n,则SelectionStart Position将与指定字符串的字符位置不匹配。

小例子(WinformsApplication。带有RichTextBox的表单):

   public Form1()
    {
        InitializeComponent();
        String sentence1 = "This is the first sentence.";
        String sentence2 = "This is the second sentence";

        String text = sentence1 + "\r\n\r\n" + sentence2;
        int start1 = text.IndexOf(sentence1);
        int start2 = text.IndexOf(sentence2);

        this.richTextBox1.Text = text;

        String subString1 = text.Substring(start1, sentence1.Length);
        String subString2 = text.Substring(start2, sentence2.Length);

        bool match1 = (sentence1 == subString1); // true
        bool match2 = (sentence2 == subString2); // true

        this.richTextBox1.SelectionStart = start1;
        this.richTextBox1.SelectionLength = sentence1.Length;
        this.richTextBox1.SelectionColor = Color.Red;

        this.richTextBox1.SelectionStart = start2;
        this.richTextBox1.SelectionLength = sentence2.Length;
        this.richTextBox1.SelectionColor = Color.Blue;

    }

RichTextBox如下所示:
enter image description here

如您所见,第二句的前两个字符没有着色。这是由\r\n\r\n产生的偏移的结果。

这是什么原因?我应该使用另一个控件来着色文本吗? 如何以可靠的方式解决问题?我尝试用String.Empty替换"\r\n\r\n",但这会产生其他偏移问题。

相关问题
Inconsistent behaviour between in RichTextBox.Select with SubString method

2 个答案:

答案 0 :(得分:2)

似乎序列\r\n仅在进行选择时计入一个字符。您可以使用\r\n替换所有\n的字符串副本进行测量。

答案 1 :(得分:1)

为了完整性(我现在坚持使用linepogls的答案):
 我找到了另一种获取SelectionStart属性索引的方法。 RichTextBox提供Find方法,可用于根据指定的字符串检索索引位置。

请注意,您要突出显示的文字可能不是唯一的并且会多次出现。您可以使用重载来指定搜索的起始位置。