Choosing a Font

This topic describes sample code that displays a Font dialog box so a user can choose the attributes of a font. The sample code first initializes a CHOOSEFONT structure, and then calls the ChooseFont function to display the dialog box.

This example sets the CF_SCREENFONTS flag to specify that the dialog box should display only screen fonts. It sets the CF_EFFECTS flag to display controls that allow the user to select strikeout, underline, and color options.

If ChooseFont returns TRUE, indicating that the user clicked the OK button, the LOGFONT structure pointed to by the lpLogFont member of the CHOOSEFONT structure contains information that describes the font and font attributes selected by the user. The rgbColors member contains the selected text color. The sample code uses this information to set the font and text color for the device context associated with the owner window.

HWND hwnd; // owner window

HDC hdc; // display device context of owner window

CHOOSEFONT cf; // common dialog box structure

static LOGFONT lf; // logical font structure

static DWORD rgbCurrent; // current text color

HFONT hfont, hfontPrev;

DWORD rgbPrev;

// Initialize CHOOSEFONT

ZeroMemory(&cf, sizeof(CHOOSEFONT));

cf.lStructSize = sizeof (CHOOSEFONT);

cf.hwndOwner = hwnd;

cf.lpLogFont = &lf;

cf.rgbColors = rgbCurrent;

cf.Flags = CF_SCREENFONTS | CF_EFFECTS;

if (ChooseFont(&cf)==TRUE) {

hfont = CreateFontIndirect(cf.lpLogFont);

hfontPrev = SelectObject(hdc, hfont);

rgbCurrent= cf.rgbColors;

rgbPrev = SetTextColor(hdc, rgbCurrent);

.

.

.

}