Win API Aligning text on a button

元气小坏坏 提交于 2019-12-11 18:31:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!