컬러 텍스트에 RichTextBox를 사용하고 있습니다. 텍스트의 다른 부분에 다른 색상을 사용한다고 가정 해 봅시다. 지금까지 문제가 없습니다.RichTextBox SelectionStart에서 줄 바꿈이있는 오프셋
현재 RichTextBox의 SelectionStart 속성에 문제가 있습니다. RichTextBox의 Text 속성에 텍스트를 설정했습니다. 텍스트에 \r\n\r\n
이 있으면 SelectionStart Position은 문자 위치를 지정된 String과 일치시키지 않습니다.
작은 예 (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은 다음과 같습니다 색깔. 이는 \r\n\r\n
에 의해 생성 된 오프셋의 결과입니다.
왜 그럴까요? 텍스트 색칠에 다른 컨트롤을 사용해야합니까? 안정적인 방법으로 문제를 해결하려면 어떻게합니까? "\r\n\r\n"
을 String.Empty로 바꾸려고했지만 다른 오프셋 문제가 발생합니다.
관련 질문는 :
Inconsistent behaviour between in RichTextBox.Select with SubString method
꽤 복잡한 문제는이 경우 두 번째 하위 문자열이 오프셋 된 문자로 시작되는지 여부를 확인하고 그에 따라 하위 문자열 매개 변수를 수정하는 것입니다. 나는이 일을 '적절한'방식으로 보길 주저하면서 대답으로 이것을 게시하지 않을 것입니다. +1 좋은 질문입니다. –