I'll begin with an example using one line of text. Let's say that you have selected a font into your device context and now want to write the text:
char *szText [] = "Hello, how are you?" ;
You want the text to start at the vertical coordinate yStart, within margins set by the coordinates xLeft and xRight. Your job is to calculate the xStart value for the horizontal coordinate where the text begins. This job would be considerably easier if the text were displayed using a fixed-pitch font, but you can't assume a fixed-pitch font in general.
First, you get the text extents of the string:
dwExtent = GetTextExtent (hdc, szText, strlen (szText)) ;
If the low word of dwExtent is larger than (xRight - xLeft), then the line is too long to fit within the margins. Let's assume it can fit.
To align the text on the left margin, you simply set xStart equal to xLeft and then write the text:
TextOut (hdc, xStart, yStart, szText, strlen (szText)) ;
This is easy. You can now add the high word of dwExtent to yStart, and you're ready to write the next line of text.
To align the text on the right margin, you use this formula for xStart:
xStart = xRight - LOWORD (dwExtent) ;
To center the text between the left and right margins, use this formula:
xStart = (xLeft + xRight - LOWORD (dwExtent)) / 2 ;
Now here's the tough job—to justify the text within the left and right margins. The distance between the margins is (xRight - xLeft). Without justification, the text is LOWORD (dwExtent) wide. The difference between these two values, which is:
xRight - xLeft - LOWORD (dwExtent)
must be equally distributed among the three space characters in the character string. It sounds like a terrible job, but it's not too bad. To do it, you call:
SetTextJustification (hdc, xRight - xLeft - LOWORD (dwExtent), 3) ;
The second parameter is the amount of space that must be distributed among the space characters in the character string. The third parameter is the number of space characters_ in this case, 3.
Now set xStart equal to xLeft and write the text with TextOut:
TextOut (hdc, xStart, yStart, szText, strlen (szText)) ;
The text will be justified between the xLeft and xRight margins.
Whenever you call SetTextJustification, it accumulates an error term if the amount of space doesn't distribute evenly among the space characters. This error term will affect subsequent GetTextExtent calls. Each time you start a new line, you should clear out the error term by calling:
SetTextJustification (hdc, 0, 0) ;