问题
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;
回答1:
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.
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.
Try this:
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;
回答2:
From https://docs.microsoft.com/en-us/windows/desktop/Controls/button-styles
Probably need to use BS_OWNERDRAW
to do what you're describing.
来源:https://stackoverflow.com/questions/51446192/win-api-aligning-text-on-a-button