CreateFont function
Namespace: WinGDI
Header: wingdi.h
Synopsis
HFONT CreateFont(
int nHeight,
int nWidth,
int nEscapement,
int nOrientation,
int fnWeight,
DWORD fdwItalic,
DWORD fdwUnderline,
DWORD fdwStrikeOut,
DWORD fdwCharSet,
DWORD fdwOutputPrecision,
DWORD fdwClipPrecision,
DWORD fdwQuality,
DWORD fdwPitchAndFamily,
LPCTSTR lpszFace
);
Parameters
| Parameter | Description |
|---|---|
nHeight | Height of characters, in logical units. |
nWidth | Average character width, in logical units. |
nEscapement | Angle of escapement (in tenths of degrees). |
nOrientation | Base-line orientation angle (in tenths of degrees). |
fnWeight | Font weight (e.g., FW_NORMAL, FW_BOLD). |
fdwItalic | Italic flag (TRUE/FALSE). |
fdwUnderline | Underline flag (TRUE/FALSE). |
fdwStrikeOut | Strikeout flag (TRUE/FALSE). |
fdwCharSet | Character set identifier (e.g., DEFAULT_CHARSET). |
fdwOutputPrecision | Output precision (e.g., OUT_DEFAULT_PRECIS). |
fdwClipPrecision | Clipping precision (e.g., CLIP_DEFAULT_PRECIS). |
fdwQuality | Output quality (e.g., DEFAULT_QUALITY). |
fdwPitchAndFamily | Pitch and family (e.g., DEFAULT_PITCH | FF_DONTCARE). |
lpszFace | Typeface name (e.g., "Arial"). |
Return Value
If the function succeeds, the return value is a handle to the created font (HFONT). If it fails, the return value is NULL. Use GetLastError for extended error information.
Remarks
- The created font can be selected into a device context (DC) with SelectObject.
- The
nHeightparameter can be a negative value to specify the character height in logical units based on the character cell. A positive value specifies the height of the character's cell. - Consider using CreateFontIndirect for more complex font definitions.
- All string parameters are Unicode if
UNICODEis defined; otherwise they are ANSI.
Example
#include <windows.h>
#include <stdio.h>
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmd, int nShow) {
HWND hwnd = GetConsoleWindow();
HDC hdc = GetDC(hwnd);
HFONT hFont = CreateFont(
-12, // nHeight
0, // nWidth
0, // nEscapement
0, // nOrientation
FW_BOLD, // fnWeight
FALSE, // fdwItalic
FALSE, // fdwUnderline
FALSE, // fdwStrikeOut
DEFAULT_CHARSET, // fdwCharSet
OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS,
DEFAULT_QUALITY,
DEFAULT_PITCH | FF_SWISS,
TEXT("Arial")
);
if (!hFont) {
MessageBox(hwnd, TEXT("Failed to create font."), TEXT("Error"), MB_ICONERROR);
return 0;
}
HFONT hOld = (HFONT)SelectObject(hdc, hFont);
TextOut(hdc, 10, 10, TEXT("Hello, GDI!"), 12);
SelectObject(hdc, hOld);
DeleteObject(hFont);
ReleaseDC(hwnd, hdc);
return 0;
}