且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Windows 窗体 TextBox 控件中设置 TAB 宽度?

更新时间:2023-12-06 09:05:16

我认为将 EM_SETTABSTOPS 消息发送到 TextBox 会起作用.

I think sending the EM_SETTABSTOPS message to the TextBox will work.

// set tab stops to a width of 4
private const int EM_SETTABSTOPS = 0x00CB;

[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr h, int msg, int wParam, int[] lParam);

public static void SetTabWidth(TextBox textbox, int tabWidth)
{
    Graphics graphics = textbox.CreateGraphics();
    var characterWidth = (int)graphics.MeasureString("M", textbox.Font).Width;
    SendMessage
        ( textbox.Handle
        , EM_SETTABSTOPS
        , 1
        , new int[] { tabWidth * characterWidth }
        );
}

这可以在 Form 的构造函数中调用,但要注意:确保首先运行 InitializeComponents.

This can be called in the constructor of your Form, but beware: Make sure InitializeComponents is run first.