Sunday, March 6, 2011

Create modified HFONT from HFONT

I using the Win32 API and C/C++. I have a HFONT and want to use it to create a new HFONT. The new font should use the exact same font metrics except that it should be bold. Something like:

HFONT CreateBoldFont(HFONT hFont) {
    LOGFONT lf;
    GetLogicalFont(hFont, &lf);
    lf.lfWeight = FW_BOLD;
    return CreateFontIndirect(&lf);
}

The "GetLogicalFont" is the missing API (as far as I can tell anyway). Is there some other way to do it? Preferrably something that works on Windows Mobile 5+.

From stackoverflow
  • You want to use the GetObject function.

    GetObject ( hFont, sizeof(LOGFONT), &lf );
    
  • Something like this - note that error checking is left as an exercise for the reader. :-)

    static HFONT CreateBoldWindowFont(HWND window)
    {
        const HFONT font = (HFONT)::SendMessage(window, WM_GETFONT, 0, 0);
        LOGFONT fontAttributes = { 0 };
        ::GetObject(font, sizeof(fontAttributes), &fontAttributes);
        fontAttributes.lfWeight = FW_BOLD;
    
        return ::CreateFontIndirect(&fontAttributes);
    }
    
    static void PlayWithBoldFont()
    {
        const HFONT boldFont = CreateBoldWindowFont(someWindow);
        .
        . // Play with it!
        .
        ::DeleteObject(boldFont);
    }
    

0 comments:

Post a Comment