Alex Rivera | Logout

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

Asked 2009-08-19T07:59:46.103
26

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

I want to use this as a quick and dirty script input box for a plugin. It really doesn't need to be fancy at all, but it would be nice if tabs were not displayed as 8 characters wide...

Edit
Report

2 Answers

16

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.

answered 2009-08-19T08:04:39.043
12

I know you are using a TextBox currently, but if you can get away with using a RichTextBox instead, then you can use the SelectedTabs property to set the desired tab width:

richTextBox.SelectionTabs = new int[] { 15, 30, 45, 60, 75};

Note that these offsets are pixels, not characters.

answered 2009-08-19T08:35:23.053

Your Answer