Home > database >  How do I change the font weight of a specific control on a dialog based window?
How do I change the font weight of a specific control on a dialog based window?

Time:11-04

I have a dialog-based window that has a "static text" control.

I want to change the font weight of that "static text" control.
I have read several subjects talking about that subject but I still don't understand how do I achieve that.

This is what I have come up with so far:

INT_PTR CALLBACK DialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    switch (uMsg) {
    case WM_INITDIALOG:
    {
        LOGFONT LogFont = {0};
        LogFont.lfWeight = FW_BOLD;
        HFONT hFont = CreateFontIndirectW(&LogFont);
        SendMessageW(hDlg, WM_SETFONT, (WPARAM) hFont, TRUE);

        return TRUE;
    }
    return FALSE;
}

How can I do that?

CodePudding user response:

Unlike static control colors, which come from the parent dialog, each control is responsible for remembering its own font.

Use WM_GETFONT to get the font the control is currently using:

HWND hwndCtl = GetDlgItem(hDlg, IDC_STATIC); // replace with your control ID
HFONT hCurFont = reinterpret_cast<HFONT>(SendMessage(hwndCtl, WM_GETFONT, 0, 0));

You can then use GetObject to query the font and fill out a LOGFONT structure:

LOGFONT lf;
GetObject(hCurFont, sizeof(lf), &lf);

You can then make changes to the LOGFONT and create a new font out of it:

lf.fwWeight = FW_BOLD;
HFONT hNewFont = CreateFontIndirect(&lf);

Finally, tell the control about the new font:

SendMessage(hwndCtl, WM_SETFONT, reinterpret_cast<WPARAM>(hNewFont), TRUE);

If you have multiple controls they can share the same font handle. The important thing to remember is that you now own that font, and it's your responsibility to free it using DeleteObject() when your dialog is destroyed (or else you'll leak the GDI resource associated with it).

  • Related