views:

323

answers:

2

Is there a graceful way to set custom tab sizes/positions in a multiline textbox in C#?

+2  A: 

You need to send the EM_SETTABSTOPS message, like this:

static class NativeMethods {
    [DllImport("user32.dll")]
    public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, ref int lParam);
}
static void SetTabs(TextBox box) {
    //EM_SETTABSTOPS - http://msdn.microsoft.com/en-us/library/bb761663%28VS.85%29.aspx
    int lParam = 16;  //Set tab size to 4 spaces
    NativeMethods.SendMessage(box.Handle, 0x00CB, new IntPtr(1), ref lParam);
    box.Invalidate();
}
SLaks
Man... you can find some nice tidbits site.
Matthew Whited
A: 

By "graceful," I mean really simple. What I ended up doing is switching the font to Courier New (Any fixed-width font would work.) and using spaces to fill in calculated tab stops with a for loop:

    for (n = sMsg.Length; n < maxLen; n++)
    {
       sMsg += " ";
    }
Jim Fell
This would be really slow as the string grows. You might be better served to look at the .PadLeft and .PadRight methods on the string.
Matthew Whited
You should be using a `StringBuilder`.
SLaks
@Matthew: That's a really good suggestion! Add it as an answer, and I'll accept it. Thanks!
Jim Fell
This *accepted* answer makes absolutely no practical sense to me!
JohnB