Setting Tabstops in TextBox for alignment

AceInfinity

Emeritus, Contributor
Joined
Feb 21, 2012
Posts
1,728
Location
Canada
Alright, so writing some random stuff in one of my code editors I noticed some cool features and decided to see how to make a regular Textbox emulate these features.

Here's a nice and easy way of setting specific points as tabstops within a Textbox control. I believe the same should work for a RichTextBox:

Code:
[DllImport("user32.dll")]
private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);

private void SetTabStops(System.Windows.Forms.TextBox textBox, int[] tabStops)
{
	const int EM_SETTABSTOPS = 0xCB;
	GCHandle gcHandle = GCHandle.Alloc(tabStops, GCHandleType.Pinned);
	IntPtr ptr = gcHandle.AddrOfPinnedObject();
	SendMessage(textBox.Handle, EM_SETTABSTOPS, new IntPtr(tabStops.Length), ptr);
	gcHandle.Free();
	textBox.Refresh();
}

private unsafe void MainMethod()
{
	string[] lines = new[]
		{
			"One\tTwo\tThree",
			"Item1\tItem2\tItem3",
			"Something1\tSomething2\tSomething3"
		};
	textBox2.Lines = lines;
	SetTabStops(textBox2, new[] {75, 150});
}

Result:
BypQ6cH.png


For a ListBox, the constant seems to be 0x192 instead of 0xCB for LB_SETTABSTOPS. The good part about this is that it's not limited to the "space character measuring" method, because we don't require a monospaced font in order for this to work.

:thumbsup2:
 

Has Sysnative Forums helped you? Please consider donating to help us support the site!

Back
Top