在Win32中更改文本的字体

Bac*_*eam 0 c++ winapi fonts

我一直在尝试使用Win32 API更改窗口中的输出字体.这是我做的,但它不起作用.我该怎么办?

hdc = BeginPaint(hWnd, &ps);
hFont = CreateFont(y_position, closest_match, escapement, orientation, FW_DONTCARE,
    no_italic, no_ul, no_xout, ANSI_CHARSET,
    OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, DRAFT_QUALITY, VARIABLE_PITCH,
    TEXT("Tekton Pro")/*"SYSTEM_FIXED_FONT"*/);
SetTextColor(hdc, RGB(255, 0, 0));
TextOut(hdc, 50, y_position, TEXT("test"), strlen("test"));
// TODO: Add any drawing code that uses hdc here...
EndPaint(hWnd, &ps);
DeleteObject(hFont);
Run Code Online (Sandbox Code Playgroud)

Pav*_*aka 5

创建字体对象后hFont,您必须调用SelectObject()将其分配给hdc.当您使用SelectObject()完字体后,再次调用以恢复旧字体(因此它不会泄露),然后再破坏您的字体:

hdc = BeginPaint(hWnd, &ps);
hFont = CreateFont(y_position, closest_match, escapement, orientation, FW_DONTCARE,
    no_italic, no_ul, no_xout, ANSI_CHARSET,
    OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, DRAFT_QUALITY, VARIABLE_PITCH,
    TEXT("Tekton Pro")/*"SYSTEM_FIXED_FONT"*/);
hOldFont = (HFONT) SelectObject(hdc, hFont); // <-- add this
SetTextColor(hdc, RGB(255, 0, 0));
TextOut(hdc, 50, y_position, TEXT("Hello from Ugur"), strlen("Hello From Ugur"));
SelectObject(hdc, hOldFont); // <-- add this
DeleteObject(hFont);  // <-- add this
// TODO: Add any drawing code that uses hdc here...
EndPaint(hWnd, &ps);
Run Code Online (Sandbox Code Playgroud)