How to: Set Tab Stops in Drawn Text

How to: Set Tab Stops in Drawn Text

 

You can set tab stops for text by calling the SetTabStops method of a StringFormat object and then passing that StringFormat object to the DrawString method of the Graphics class.

System_CAPS_noteNote

The System.Windows.Forms.TextRenderer does not support adding tab stops to drawn text, although you can expand existing tab stops using the TextFormatFlags.ExpandTabs flag.

Example

The following example sets tab stops at 150, 250, and 350. Then, the code displays a tabbed list of names and test scores.

The following illustration shows the tabbed text.

Fonts Text

The following code passes two arguments to the SetTabStops method. The second argument is an array that contains tab offsets. The first argument passed to SetTabStops is 0, which indicates that the first offset in the array is measured from position 0, the left edge of the bounding rectangle.

string text = "Name\tTest 1\tTest 2\tTest 3\n";
text = text + "Joe\t95\t88\t91\n";
text = text + "Mary\t98\t84\t90\n";
text = text + "Sam\t42\t76\t98\n";
text = text + "Jane\t65\t73\t92\n";

FontFamily fontFamily = new FontFamily("Courier New");
Font font = new Font(
   fontFamily,
   12,
   FontStyle.Regular,
   GraphicsUnit.Point);
Rectangle rect = new Rectangle(10, 10, 450, 100);
StringFormat stringFormat = new StringFormat();
SolidBrush solidBrush = new SolidBrush(Color.FromArgb(255, 0, 0, 255));
float[] tabs = { 150, 100, 100, 100 };

stringFormat.SetTabStops(0, tabs);

e.Graphics.DrawString(text, font, solidBrush, rect, stringFormat);

Pen pen = Pens.Black;
e.Graphics.DrawRectangle(pen, rect);

Compiling the Code

Show:
© 2016 Microsoft