Using Color when Writing Text

You can add color to the text you write by setting the text and background colors of the device context. The text color determines the color of the character to be written; the background color determines the color of everything in the character cell except the character. GDI writes the entire character cell (the rectangle enclosing the character) when it writes text. A character cell usually has the same width and height as the character.

You can set the text and background colors by using the SetTextColor and SetBkColor functions. The following example sets the text color to red and the background color to green:

SetTextColor(hDC, RGB(255,0,0));

SetBkColor(hDC, RGB(0,255,0));

When you first create a device context, the text color is black and the background color is white. You can change these colors at any time.

NOTE:

If you are using a common display context obtained with GetDC or BeginPaint, your colors are lost each time you release the context, so you need to set them each time you retrieve the display context.

The background color applies only when the background mode is opaque. The background mode determines whether the background color in the character cell has any effect on what is already on the display surface. If the mode is opaque, the background color overwrites anything already on the display surface; if it is transparent, anything on the display surface that would otherwise be overwritten by the background is preserved. You can set the background mode by using the SetBkMode function, or you can retrieve the current mode by using the GetBkMode function. Similarly, you can retrieve the current text and background color by using the GetTextColor and GetBkColor functions.