Win API对齐按钮上的文本 [英] Win API Aligning text on a button
问题描述
有没有一种方法可以使按钮内的文本水平和垂直居中对齐?
Is there a way to center align the text inside a button both horizontally and vertically?
case WM_DRAWITEM:
{
LPDRAWITEMSTRUCT Item;
Item = (LPDRAWITEMSTRUCT)lParam;
SelectObject(Item->hDC, CreateFont(17, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH, "Arial Black"));
FillRect(Item->hDC, &Item->rcItem, CreateSolidBrush(0xE0E0E0) );
SetBkMode(Item->hDC, 0xE0E0E0);
SetTextColor(Item->hDC, RGB(255,255,255));
int len;
len = GetWindowTextLength(Item->hwndItem);
LPSTR lpBuff;
lpBuff = new char[len+1];
GetWindowTextA(Item->hwndItem, lpBuff, len+1);
DrawTextA(Item->hDC, lpBuff, len, &Item->rcItem, DT_CENTER);
}
break;
推荐答案
您已经在使用 DT_CENTER
标志可将文本水平居中。 DrawText()
还具有 DT_VCENTER
和 DT_SINGLELINE
标志居中垂直文本。只需将标志组合在一起即可。
You are already using the DT_CENTER
flag to center the text horizontally. DrawText()
also has DT_VCENTER
and DT_SINGLELINE
flags to center the text vertically. Simply combine the flags together.
此外,您还有资源和内存泄漏。您正在从 CreateFont()
, HBRUSH
HFONT >来自 CreateSolidBrush()
,而文本缓冲区来自 new []
。使用完它们后,您需要释放它们。
Also, you have resource and memory leaks. You are leaking the HFONT
from CreateFont()
, the HBRUSH
from CreateSolidBrush()
, and the text buffer from new[]
. You need to free them all when you are done using them.
尝试一下:
case WM_DRAWITEM:
{
LPDRAWITEMSTRUCT Item = reinterpret_cast<LPDRAWITEMSTRUCT>(lParam);
HFONT hFont = CreateFont(17, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH, TEXT("Arial Black"));
HFONT hOldFont = (HFONT) SelectObject(Item->hDC, hFont);
HBRUSH hBrush = CreateSolidBrush(RGB(0xE0, 0xE0, 0xE0));
FillRect(Item->hDC, &Item->rcItem, hBrush);
DeleteObject(hBrush);
SetBkMode(Item->hDC, TRANSPARENT); // <-- 0xE0E0E0 was not a valid mode value!
SetTextColor(Item->hDC, RGB(255,255,255));
int len = GetWindowTextLength(Item->hwndItem) + 1;
LPTSTR lpBuff = new TCHAR[len];
len = GetWindowText(Item->hwndItem, lpBuff, len);
DrawText(Item->hDC, lpBuff, len, &Item->rcItem, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
delete[] lpBuff;
SelectObject(Item->hDC, hOldFont);
DeleteObject(hFont);
}
break;
这篇关于Win API对齐按钮上的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!