Search code examples
c++winapiembedded-resource

FindResource returns NULL when trying to load a font from resources


I am trying to load a font from my resources. This is the call I use, which currently returns NULL and therefore fails:

HRSRC rsrcData = FindResource(NULL, MAKEINTRESOURCE(IDF_ROBOTBLACK), L"FONT");

I added the font resource to my Resource.rc file, which now lists the following:

/////////////////////////////////////////////////////////////////////////////
//
// Font
//

IDF_ROBOTBLACK          FONT                    "Resources\\Fonts\\Roboto\\Roboto-Black.ttf"

Additionally, this is what my Resource.h looks like:

#define IDF_ROBOTBLACK                  108

As far as I can tell, this should be all there is to the whole process.

I already successfully managed to load another resource format, "PNG", which was added as a new, custom resource type as well, following the same procedure while only replacing "FONT" with "PNG" where it is due.

However, compared to my "PNG" loading approach, the "FONT" is never found. FindResource returns NULL, no matter what happens.

The error code returend by GetLastError() is 1813.

My concern is that .ttf is not really supported at all. I previously added all kinds of formats to my solutions resources, like .exe and .png, .jpg, but .ttf was not even suggested in the file picker when adding the resource.

Is it just not meant to be stored this way?


Solution

  • FONT is a standard resource type, unlike PNG. Therefore you must use RT_FONT instead of L"FONT".

    The resource declaration can remain as:

    IDF_ROBOTBLACK FONT "filename.ttf"
    

    The resource must then be located as follows:

    FindResource(NULL, MAKEINTRESOURCE(IDF_ROBOTBLACK), RT_FONT); 
    

    Alternatively, you could use:

    IDF_ROBOTBLACK xfont "filename.ttf"
    

    FindResource(NULL, MAKEINTRESOURCE(IDF_ROBOTBLACK), L"xfont"); 
    

    This would work because xfont is not a standard resource (same as PNG).

    Or, you can always use RCDATA and RT_RCDATA.