Using Multiple Fonts in a Line

If you are developing an application that uses a variety of fonts—a word processor, for instance—you will probably want to use more than one font in a line of text. To do so, you will need to write the text in each font separately. The TextOut function cannot change fonts for you.

The main difficulty with using more than one font in a line of text is that you need to keep track of how far each call to TextOut advances the line of text, so that you can supply the appropriate starting location for the next part of the line. If you are using variable-width fonts, keeping track of the length of a written string can be difficult. However, Windows provides the GetTextExtent function, which computes the length of a given string by using the widths of characters in the current font.

One way to write a line of text that contains multiple fonts is to use the GetTextExtent function after each call to TextOut and add the length to a current position. The following example shows how to write the line This is a sample string. using italic characters for the word sample and bold characters for all others:

X = 10;

SelectObject(hDC, hBoldFont);

TextOut(hDC, X, 10, “This is a ”, 10);

X = X + LOWORD(GetTextExtent(hDC, “This is a ”, 10));

SelectObject(hDC, hItalicFont);

TextOut(hDC, X, 10, “sample ”, 7);

X = X + LOWORD(GetTextExtent(hDC, “sample ”, 7));

SelectObject(hDC, hBoldFont);

TextOut(hDC, X, 10, “string.”, 7);

In this example, the SelectObject function sets the font to be used in the subsequent TextOut function. The hBoldFont and hItalicFont font handles are assumed to have been previously created using the CreateFont function. Each TextOut function writes a part of the line, then the GetTextExtent function computes the length of that part. GetTextExtent returns a double-word value containing both the length and height. You need to use the LOWORD macro to retrieve the length. This length is added to the current position to determine the starting location of the next part of the line.

Another way to write a line with multiple fonts is to create a function that consolidates all the required actions into a single call. The following example shows such a function:

WORD StringOut(hDC, X, Y, lpString, hFont)

HDC hDC;

short X;

short Y;

LPSTR lpString;

HANDLE hFont;

{

HANDLE hPrevFont;

hPrevFont = SelectObject(hDC, hFont);

TextOut(hDC, X, Y, lpString, lstrlen(lpString));

SelectObject(hDC, hPrevFont);

return (LOWORD(GetTextExtent(hDC, lpString, lstrlen(lpString)));

}

This function writes the string in the given font, then resets the font to its previous setting and returns the length of the written string. The following example shows how to write the line, This is a sample string.:

X = 10;

X = X + StringOut(hDC, X, 10, “This is a ”, hBoldFont);

X = X + StringOut(hDC, X, 10, “sample ”, hItalicFont);

StringOut(hDC, X, 10, “string.”, hBoldFont);