【发布时间】: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