【问题标题】:RichTextBox SelectionStart offset with linebreaks带有换行符的 RichTextBox SelectionStart 偏移量
【发布时间】:2013-10-10 10:22:16
【问题描述】:

我将 RichTextBox 用于彩色文本。假设我想为文本的不同部分使用不同的颜色。到目前为止一切正常。

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

小例子(WinformsApplication.Form with a 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 如下所示:

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

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

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

【问题讨论】:

  • 一种非常“笨拙”的方法是确定第二个子字符串(在这种情况下)是否前面有那些字符会抛出您的偏移量,并相应地修改您的子字符串参数。顺便说一句,我不会将此作为答案发布,因为我坚持要看到“正确”的做法。 +1 提出好问题。

标签: c# winforms richtextbox


【解决方案1】:

似乎序列\r\n 仅在进行选择时才算作一个字符。您可以在所有\r\n 替换为\n 的字符串副本中进行测量。

【讨论】:

  • 似乎解决了我的问题 =) 你知道为什么 RichTextBox 会这样吗?
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多