RichTextBox

クラス階層

  • System.ComponentModel.Component
    • System.Windows.Forms.Control
      • System.Windows.Forms.TextBoxBase
        • System.Windows.Forms.TextBox
        • System.Windows.Forms.RichTextBox
        • System.Windows.Forms.MaskedTextBox

TextBoxとの違いは、TextBox と RichTextBox - RichTextBox の概要にあります。

プロパティ

プロパティ 内容
RichTextBoxScrollBars ScrollBars 表示するスクロールバーの種類

WordWrapがtrueのときは、この設定に関わらず水平スクロールバーは表示されない

プロパティ - RichTextBox クラス (System.Windows.Forms) | Microsoft Learn

選択位置の変更

  • SelectionStartプロパティ … 選択されているテキストの開始位置
  • SelectionLengthプロパティ … 選択されているテキストの文字数
  • Select(Int32, Int32)メソッド … 開始位置から指定の文字数を選択する
  • SelectAll() … すべてのテキストを選択する

書式の指定

書式の変更は、現在選択されているテキストと、それ以降に入力されるテキストに適用されます。

フォントの色

richTextBox1.Clear();
richTextBox1.SelectedText = "ABC";

richTextBox1.SelectionColor = Color.Red;
richTextBox1.SelectedText = "Red";

richTextBox1.SelectionColor = Color.Blue;
richTextBox1.SelectedText = "Blue";

これを実行すると、コントロール内のテキストは「ABCRedBlue」と表示されます。RichTextBox.SelectionColor プロパティ (System.Windows.Forms) | MSDN

フォントのスタイル

richTextBox1.Clear();
richTextBox1.SelectedText = "ABC";

richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold);
richTextBox1.SelectedText = "Bold";

richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Italic);
richTextBox1.SelectedText = "Italic";

これは「ABCBoldItalic」となります。RichTextBox.SelectionFont プロパティ (System.Windows.Forms) | MSDN

多量のテキストの追加

テキストの追加をくり返すのは時間がかかります。しかしRichTextBoxにはBeginUpdate()のようなメソッドはなく、SuspendLayout()はコントロールの内容の更新には作用しません。Is there BeginUpdate, EndUpdate with the RichTextBox control?

この問題に対処するには、テキストを一括して追加するようにします。それがプレーンテキストならば、文字列を作成した上でそれをTextプロパティに設定します。書式設定されたテキストならば、Rtfプロパティに設定します。そのときRTF形式でテキストを作成するには作業用のRichTextBoxを作成し、そこにテキストを追加した上で、そのRtfプロパティをコピーすると簡単です。

RichTextBox temp = new RichTextBox();

temp.SelectedText = etc;
temp.SelectedText = etc;
...

richTextBox.Rtf = temp.Rtf;
Microsoft Learnから検索