色付きのテキスト RichTextBox を出力する関数があります。一致するものはすべて赤く、一致しないテキストは黒くする必要があります。次の関数は、エントリが挿入されているときに RichTextBox コンテンツの色を変更しようとします ( RichTextBox 文字列のさまざまな部分に色を付けるのと同じように)
public void OutputColoredMatches(String InputText, MatchCollection Matches, RichTextBox OutputBox)
{
int LastMatchEndIndex = OutputBox.TextLength;
foreach (Match CurrentMatch in Matches)
{
OutputBox.SelectionColor = Color.Black;
OutputBox.AppendText(InputText.Substring(LastMatchEndIndex, CurrentMatch.Index - LastMatchEndIndex));
OutputBox.SelectionColor = Color.Red;
OutputBox.AppendText(InputText.Substring(CurrentMatch.Index, CurrentMatch.Length));
LastMatchEndIndex = CurrentMatch.Index + CurrentMatch.Length;
}
OutputBox.SelectionColor = Color.Black;
OutputBox.Text += InputText.Substring(LastMatchEndIndex, InputText.Length - LastMatchEndIndex);
}
この関数は、選択色を黒に設定した後にのみ、黒であるべきテキストを追加し、選択色を赤に設定した後にのみ、見つかった一致するテキストを追加します。コードをステップ実行してテキストが正しく挿入されていることを確認しても、出力はすべて黒です。
また、テキストのすべて (または一部) を挿入するように変更してから、RichTextBox の選択範囲のサイズを変更しようとしました。次に、選択色を設定しますが、これも機能しませんでした。選択範囲が適切な場所で開始および終了することを確認し、再確認したにもかかわらず、すべてのテキストは最後に赤または黒のいずれかでした. (似たようなことを試しました: RichTextBox でテキストを選択的に色付けします)。これは、テキストの一部を挿入し、その色を変更する関数の別のバリエーションです。また、デバッガーでこれを実行し、期待どおりにアイテムを選択し、色を設定していることを確認しました。すべての出力が黒でした:
public void OutputColoredMatches(String InputText, MatchCollection Matches, RichTextBox OutputBox)
{
int SelPos = 0;
int LastMatchEndIndex = OutputBox.TextLength;
foreach (Match CurrentMatch in Matches)
{
SelPos = OutputBox.TextLength;
OutputBox.AppendText(InputText.Substring(LastMatchEndIndex, CurrentMatch.Index - LastMatchEndIndex));
OutputBox.SelectionStart = SelPos;
OutputBox.SelectionLength = OutputBox.TextLength - SelPos;
OutputBox.SelectionColor = Color.Black;
SelPos = OutputBox.TextLength;
OutputBox.AppendText(InputText.Substring(CurrentMatch.Index, CurrentMatch.Length));
OutputBox.SelectionStart = SelPos;
OutputBox.SelectionLength = OutputBox.TextLength - SelPos;
OutputBox.SelectionColor = Color.Red;
LastMatchEndIndex = CurrentMatch.Index + CurrentMatch.Length;
}
OutputBox.SelectionColor = Color.Black;
OutputBox.Text += InputText.Substring(LastMatchEndIndex, InputText.Length - LastMatchEndIndex);
}
具体的に言うと、正規表現 's' と入力テキスト 'asdf' がある場合、この関数は 'a' を出力ボックスに挿入します。次に、選択位置を 0 に設定し、選択長を 1 に設定してから、色を黒に設定します。次に、's' を挿入し、選択位置を 1、長さを 1、色を赤にします。次に、「df」を挿入して、選択位置を 2、長さを 2、色を黒に設定します。その後、すべての出力が黒になります。
また、選択の開始位置と長さでさまざまなことを試してから、テキストを挿入しても効果がありませんでした。テキストボックスに漠然と関連するだけで、何か間違ったことをしている可能性が高いと思います。
私が注意を払っていない可能性のある着色動作に他に何が影響する可能性がありますか.