richTextBox 内の単語を検索するプログラムを作成しようとしています。ほとんどの部分を作成しましたが、何かを見逃しているようです。見つかった単語に色を付けたいので、次のように書きました。
private void button1_Click(object sender, RoutedEventArgs e)
{
richTextBox1.SelectAll();
string words = richTextBox1.Selection.Text; // to get the the whole text
int length = words.Length; // length of text
string search = textBox1.Text; // the word being searched for
int search_length = search.Length;
int index =0; // to go through the text
int endIndex = 0; // the end of the got word
// pointer to the begining and the ending of the word which will be colored.
TextPointer start_pointer, end_pointer;
if(length>0 &&search_length>0) // text exists
while(index<length-search_length)
{
index = words.IndexOf(search, index);
if (index < 0) // not found
break;
endIndex = index+search.Length-1; // last char in the word
start_pointer = richTextBox1.Document.ContentStart.GetNextInsertionPosition(LogicalDirection.Forward).GetPositionAtOffset(index, LogicalDirection.Forward);
end_pointer = richTextBox1.Document.ContentStart.GetNextInsertionPosition(LogicalDirection.Forward).GetPositionAtOffset(endIndex + 1, LogicalDirection.Forward);
TextRange got = new TextRange(start_pointer, end_pointer);
//just for debugging
MessageBox.Show("start =" + index + " end =" + endIndex + " " + got.Text);
got.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Blue));
index =endIndex+1;
}
最初の単語は色付きです。しかし、次の単語はそうではありません (つまり、テキストが「学校に行き、市場に行きます」で、「行く」という単語が検索され、検索ボタンを押した場合、結果は次のようになります。最初の「go」には色を付けますが、2 番目の「go」には色を付けません)。
これは、textRange が正しく機能していないか、TextPointer に問題があるために発生していると推測されます。さらに、 index と endIndex は正しいです - 私はそれらをテストしました。
私はあなたの助けに感謝します。