Search code examples
cwinapibitmapcross-compilingembedded-resource

FindResource works, LoadBitmap doesn't, LoadImage from disk works


I am trying to use LoadBitmap to load an image from a resource file.

I've verified that the resource is linked correctly -- examining the final EXE with a hex editor shows that the bitmap is packed inside the EXE correctly.

I've also verified that the bitmap is valid -- using LoadImage with LR_LOADFROMFILE to load the bitmap from disk at runtime works fine and I see it appear when I add it to a gui element later.

I've verified that the ID that I use to access the resource is valid as well -- the FindResource function finds the resource and SizeofResource prints the exact expected number of bytes for the bitmap.

So I have a valid linked resource, a valid ID, and a loadable bitmap.

However, LoadBitmap returns NULL and so does LoadImage if I load from a resource instead of from disk. GetLastError returns 0.

Any ideas? Am I #defining RT_BITMAP in resource.rc correctly?

Thanks.

resource.h

#define     BMP_TEST_ID         2

resource.rc

#include "resource.h" // defines BMP_TEST_ID
#define     RT_BITMAP           2 

BMP_TEST_ID RT_BITMAP "TEST24.BMP"

test.c

#include <windows.h> // defines RT_BITMAP as MAKEINTRESOURCE(2)
#include "resource.h" // defines BMP_TEST_ID

HINSTANCE instance = GetModuleHandle(NULL);
if (!instance) { /* handle error */ }

/* find a bitmap resource with the ID we want -- OK! */
HRSRC rsc = FindResource(instance, RT_BITMAP, MAKEINTRESOURCE(BMP_TEST_ID));
if (!rsc) { /* handle error */ }

/* prints the exact size of the found resource -- GIVES CORRECT OUTPUT */
printf("SizeofResource: %d\n", (int) SizeofResource(instance, rsc));

// ***** THIS BIT DOESN'T WORK *****
/* load bitmap resource -- FAIL! */
HBITMAP bitmap = (HBITMAP)LoadBitmap(instance, MAKEINTRESOURCE(BMP_TEST_ID));
if (!bitmap) { /* handle error */ }

/* load bitmap from file -- OK! */
HBITMAP bitmap2 = (HBITMAP)LoadImage (NULL, "TEST24.BMP", IMAGE_BITMAP,0,0,LR_LOADFROMFILE);
if (!bitmap2) { /* handle error */ }

My compiler is amd64-mingw32msvc-gcc 4.6.3


Solution

  • First, you should not have to define RT_BITMAP at all. It is already defined through winuser.h to be included in your c/cpp files. And it turns out you don't need it in your resource file anyway.

    The BITMAP resource type will properly assign the right resource type id for your bitmap file. Change your bitmap resource declaration to be:

    BMP_TEST_ID BITMAP "TEST24.BMP" 
    

    And you should be good to go.