非IT企業に勤める中年サラリーマンのIT日記

非IT企業でしかもITとは全く関係ない部署にいる中年エンジニア。唯一の趣味がプログラミングという”自称”プログラマー。

C#のTextBoxやRichTextBoxのタブサイズを変える方法

   

C#のTextBoxやRichTextBoxではTabサイズを変更するプロパティやメソッドは存在しません。変更する場合はWindowsAPIを使う必要があります。

デフォルトのタブ幅は5文字のようです。個人的にはこれだとちょっと大きいんですよね。3文字くらいが個人的にちょうどいいです。

[ad#top-1]

Windows API を使う

最初に初期設定として以下の宣言をしておきます。コンストラクタの上あたりに書きましょう。

//Tabサイズの設定
[System.Runtime.InteropServices.DllImport( "User32.dll" )]
static extern IntPtr SendMessage( IntPtr hWnd, int msg, int wParam, int[] lParam );
 

 

で、TextBoxまたはRichTextBoxを生成した後に、以下のコードを追加しましょう。例はタブサイズを3文字としています。(tabSize変数がそれ)

//タブサイズの設定
int tabSize = 3;
int tabWidth = (int)(tabSize * 3 * 96 / 72);
SendMessage( textBox.Handle, 0x00CB, 1, new int[]{ tabWidth } );
 

 

tabSize値に、3と96を掛けて72で割った値をSendMessageの第二引数に入れると、文字tabSize個分のタブになります。上の例ではタブサイズを3で設定しています。

実行すると以下の通りタブサイズが3となりました。

 

文字サイズを変えてもご覧の通り3文字分のタブサイズになってくれます。

 

ソースコード全文

こちらがソースコード全文です。RichTextBoxを使用しているので、前に紹介したフォントが勝手に変わらないためのAPIも入れています。

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;

class TabTest{
  static void Main(string[] args){
    Application.Run(new MainWindow(args));
  }
}

class MainWindow : Form{
  private RichTextBox textBox;

  //RichTextBoxでフォントが勝手に変わらないためのAPI用
  private const uint IMF_DUALFONT = 0x80;
  private const uint WM_USER = 0x0400;
  private const uint EM_SETLANGOPTIONS = WM_USER + 120;
  private const uint EM_GETLANGOPTIONS = WM_USER + 121;
  [System.Runtime.InteropServices.DllImport("USER32.dll")]
  private static extern uint SendMessage(System.IntPtr hWnd, uint msg, uint wParam, uint lParam);

  //Tabサイズの設定
  [System.Runtime.InteropServices.DllImport( "User32.dll" )]
  static extern IntPtr SendMessage( IntPtr hWnd, int msg, int wParam, int[] lParam );

  public MainWindow(string[] args){
    this.StartPosition = FormStartPosition.CenterScreen;
    this.Width = 600;
    this.Height =400;
    this.Text = "テキストボックステスト";

    textBox = new RichTextBox(){
      Dock = DockStyle.Fill,
      Font = new Font("MS ゴシック", 20),
      AcceptsTab = true,
      WordWrap = false,
      Parent=this,
    };
    textBox.KeyDown += new KeyEventHandler(keyDowned);

    //RichTextBoxでフォントが勝手に変わらないための処置
    uint lParam;
    lParam = SendMessage(this.textBox.Handle, EM_GETLANGOPTIONS, 0, 0);
    lParam &= ~IMF_DUALFONT;
    SendMessage(this.textBox.Handle, EM_SETLANGOPTIONS, 0, lParam);

    //タブサイズの設定
    int tabSize = 3;
    int tabWidth = (int)(tabSize * 3 * 96 / 72);
      SendMessage( textBox.Handle, 0x00CB, 1, new int[]{ tabWidth } );
    }
}
 

 

[ad#ad-1]

スポンサーリンク

 - C#応用編