LoginSignup
4
5

More than 5 years have passed since last update.

C#のRichTextBoxで描画処理を追加する

Last updated at Posted at 2016-12-22

やりたいこと

  • 背景色を1行全体に表示されるようにしたい。

どういうこと?

SelectionBackColorで背景色を指定した場合、選択範囲のみに背景が適用されます。
逆に、行をしていして背景色をへんこうするということができません。
Rich Text Format(RTF)的にそのような考えはないのでしょう。

背景

ログビューワーを作成していて、特定のキーワードを見つけたら背景色を変更するようにしています。
しかしながら、文字列のある範囲しか背景色は変わらず、行全体を着色できません。

どうするか

自分で描画処理を追加するしかありません。
RichTextBoxはListBoxやComboBoxのようにDrawItemもなくオーナードローができないということなので、WM_PAINTをフックして、RichTextBoxの描画の後に付け加える形で実現することにします。

実装

private const Int32 WM_PAINT = 0x000F;

protected override void WndProc(ref System.Windows.Forms.Message m)
{
    base.WndProc(ref m);
    if (m.Msg == WM_PAINT)
    {
        using (Graphics graphic = base.CreateGraphics())
            OnPaint(new PaintEventArgs(graphic, base.ClientRectangle));
    }

    protected override void OnPaint(PaintEventArgs pe)
    {
        using (Brush brush = new SolidBrush(Color.Pink))
        {
            // 改行検索
            Regex regex = new Regex("\n");
            foreach (Match match in regex.Matches(this.Text))
            {
                Point point = this.GetPositionFromCharIndex(match.Index);
                pe.Graphics.FillRectangle(brush, point.X, point.Y, pe.ClipRectangle.Width, 18);
            }
        }
    }

※ちなみに、このままだとすべての改行のある行の後ろの背景色が変わりますので、背景色を変更している行のみ特定するなどの対処が必要になります

サンプル画面

実装前

alt

実装後

alt

ちなみにこのサンプル画面の動作の様子は次の記事内の動画から確認できます。

元となっている記事

参考サイト

以上

4
5
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
4
5