How to set the TAB width in a Windows Forms TextBox control?

前端 未结 6 500
独厮守ぢ
独厮守ぢ 2020-12-17 08:57

Given a WinForms TextBox control with MultiLine = true and AcceptsTab == true, how can I set the width of the tab character displayed?

I wa

6条回答
  •  执念已碎
    2020-12-17 09:27

    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 }
            );
    }
    

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

    • Link at MSDN
    • Here is another link

提交回复
热议问题