gpt4 book ai didi

c# - RichTextBox SelectionStart 用换行符偏移

转载 作者:行者123 更新时间:2023-11-30 22:13:12 24 4
gpt4 key购买 nike

我正在为彩色文本使用 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 看起来像这样:
enter image description here

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

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

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

最佳答案

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

关于c# - RichTextBox SelectionStart 用换行符偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19293189/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com