Search code examples
c++buildertbitmap

TBitmap LoadFromResourceName is not working


I am using C++Builder. I have 70 small bitmap images in a .res file.

My code using MyBitMap->LoadFromResourceID works and loads the bitmap from the .res file.

    TBitmap *MyBitMap = new Graphics::TBitmap();
    MyBitMap->LoadFromResourceID( (int)HInstance, 2 );
    delete MyBitMap;
    MyBitMap=NULL;

The code below using MyBitMap->LoadFromResourceName gives the error "raised exception class EResNotFound with message 'Resource cp2.bmp not found'."

    TBitmap *MyBitMap = new Graphics::TBitmap();
    const UnicodeString MyName = "cp2.bmp";
    MyBitMap->LoadFromResourceName((int)HInstance, MyName );// Error Here
    delete MyBitMap;
    MyBitMap=NULL;

Here is the top of my .rc file. I have setup all the bitmaps with an ID number and the file name. Loading using the name does not work. Can you show how to use LoadFromResourceName. Thanks.

99 BITMAP "cp0.bmp"
1 BITMAP "cp1.bmp"
2 BITMAP "cp2.bmp"
3 BITMAP "cp3.bmp"
4 BITMAP "cp4.bmp"
5 BITMAP "cp5.bmp"
6 BITMAP "cp6.bmp"
7 BITMAP "cp7.bmp"
8 BITMAP "cp8.bmp"
9 BITMAP "cp9.bmp"

I tried every solution I could find in Google, the Embarcadero Wiki Docs and on ChatGPT.


Solution

  • LoadFromResourceName() is failing because none of your image resources are named cp2.bmp. That is just the filename that the resource compiler pulls image data from while compiling the .res file. The actual IDs in your .res are 99, 1, 2, 3, etc. That is why LoadFromResourceID() works.

    Resources can't have both numeric IDs and non-numeric names, they can have one or the other.

    If you want to assign names to your resources, it should look more like this instead:

    CP0 BITMAP "cp0.bmp"
    CP1 BITMAP "cp1.bmp"
    CP2 BITMAP "cp2.bmp"
    CP3 BITMAP "cp3.bmp"
    CP4 BITMAP "cp4.bmp"
    CP5 BITMAP "cp5.bmp"
    CP6 BITMAP "cp6.bmp"
    CP7 BITMAP "cp7.bmp"
    CP8 BITMAP "cp8.bmp"
    CP9 BITMAP "cp9.bmp"
    
    TBitmap *MyBitMap = new Graphics::TBitmap();
    const UnicodeString MyName = _D("CP2");
    MyBitMap->LoadFromResourceName((NativeUInt)HInstance, MyName);
    delete MyBitMap;
    MyBitMap = NULL;
    

    Refer to MSDN for more details:

    About Resource Files

    Resource-Definition Statements

    BITMAP resource