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

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

C#: TextBoxのタブ幅を変えるには何故かWin32APIを使う必要あり。

      2016/06/11

[ad#top-1]
 
TextBoxのタブ幅のカスタマイズってそこそこ需要ありそうですが、なぜかC#ではWin32APIを使用しないとできないみたいです。ちなみに、JavaではJTextAreaにタブ幅を変えるメソッドが存在しています。(ただ、JTextPaneにはない。この違いの意味がようわからん。)

TextBoxで、Win32APIを使ったタブ幅の変更方法を記しておきます。

こちらがソースコード。コンストラクタの上に書かれている数行のコードがWin32APIの呼び出し。最後に書かれているコードがタブ幅を設定している部分です。{16}の16が4文字相当。

using System;
using System.Drawing;
using System.Windows.Forms;
class Mainwindow{
   static void Main(){
      Application.Run(new Test());
   }
}
class Test : Form{
   //Win32 API
   [System.Runtime.InteropServices.DllImport(“User32.dll”)]
   static extern IntPtr SendMessage(
       IntPtr hWnd, int msg, int wParam, int [] lParam);
   public Test(){
      this.StartPosition = FormStartPosition.CenterScreen;
      this.Width = 600;
      this.Height = 250;
      this.Text = “Test”;
      TextBox textBox = new TextBox(){
         Font = new Font(“Courier New”, 10),
         ScrollBars = ScrollBars.Both,
         WordWrap = false,      //折り返さない
         AcceptsTab = true,      //[Tab]キーでTab文字有効
         Dock = DockStyle.Fill,
         BorderStyle = BorderStyle.FixedSingle,
         Multiline = true,
         Parent=this,
      };
      //Tab幅を指定
      const int EM_SETTABSTOPS = 0x00CB;
      SendMessage(textBox.Handle, EM_SETTABSTOPS, 1, new int[] {16});
   }
}

 
[ad#ad-1]

スポンサーリンク

 - C#応用編