LoginSignup
1
1

More than 5 years have passed since last update.

C#でRichTextBoxに書式を損なわずにテキストの追記を行う(Rtfでの追記)

Last updated at Posted at 2016-12-22

やりたいこと

  • RichTextBoxにて書式変更した後にテキストを追加しても書式を損なわないようにしたい

背景

ログビューワーを作成していた際、特定キーワードを発見したら背景色を変更するようにしていましたが、背景色が反映されず、次のような簡易コードで確認してみました。

richTextBox2.Text = "a";
richTextBox2.Update(); // step1

richTextBox2.Text += "b";
richTextBox2.Select(1, 1);
richTextBox2.Update(); // step2

richTextBox2.SelectionBackColor = Color.Pink;
richTextBox2.Update(); // step3

richTextBox2.Text += "c";
richTextBox2.Update(); // step4

step3で背景色が適用されるも、step4で背景色が消えます。
RichTexBoxはデータの実態がRich Text Format (Rtf) なので当然といえば当然なのですね。

実装

今回は、追記するテキストを別のRichTextBoxに貼り付けて書式変更した後、本体のRichTextBoxに貼り付ける方法にしました。

RichTextBox rich = new RichTextBox();
rich.Text = addText;
rich.Select(0, rich.TextLength);
rich.SelectionBackColor = Color.Pink;

richTextBox2.SelectionStart = richTextBox2.TextLength;
richTextBox2.SelectedRtf = rich.Rtf;

元となっている記事

以上

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1