您还可以使用 DrawText 函数。只需将 DT_CALCRECT 标志传递给函数。甚至 GetTextMetrics - 我都在这里使用过。它们是普通的、普通的 win32 函数。适用于您希望尝试的任何支持 win32 progs 的编译器。VS、GCC、Borland等
代码片段:
HDC hDC;
TEXTMETRIC textMetric;
HFONT hFont, hOldFont;
int sizeInPpoints, lineHeight;
RECT textRect;
char *buffer = "Comprimento em pixels desta string!";
hDC = GetDC(hwnd);
sizeInPpoints = MulDiv(10, GetDeviceCaps(hDC, LOGPIXELSY), 72);
hFont = CreateFont(-sizeInPpoints, 0, 0, 0, FW_NORMAL, 0, 0, 0, 0, 0, 0, 0, 0, "Courier New");
hOldFont = (HFONT)SelectObject(hDC, hFont);
GetTextMetrics(hDC, &textMetric);
lineHeight = textMetric.tmHeight; // character height in current font
textRect.left = textRect.right = textRect.top = textRect.bottom = 0;
DrawText(hDC, buffer, strlen(buffer), &textRect, DT_CALCRECT);
printf("Size of text calculated by DrawText: [%d x %d]\n", textRect.right, textRect.bottom);
printf("Height of text calculated by GetTextMetrics: %d\n", lineHeight);
输出:
Size of text calculated by DrawText: [280 x 16]
Height of text calculated by GetTextMetrics: 16