Search code examples
delphiembedded-resourceresource-file

Delphi: Loop data in resource file


I need to loop inside a resource file and and load all BMP files with the following statement; bBitmap.Handle := LoadBitmap(hInstance, 'IMAGE_NAME');

How do I loop a resource file; do I have to do a regular IO operation and treat it like a text file? I can read each line and create a list of bitmap names than on a separate loop execute the above statement to load bitmaps. Or is there a built-in method in Delphi libraries to do this operation?

FILE_NAME_1 BITMAP "btnFile1.bmp"
FILE_NAME_2 BITMAP "btnFile2.bmp"
....


Solution

  • EnumResourceNames as suggested by Ken White worked perfectly, and it's pretty simple to implement. Couldn't accept it as an answer because he left a comment only.

    Here's my solution using the suggestion;

    Inside the procedure where I load my images, I added the following lines of code;

    var
      returnVal:bool;
      hMdl: HMODULE;
    begin
      hMdl:=LoadLibraryEX('FileNameWithResources.exe',0,LOAD_LIBRARY_AS_DATAFILE);
      // I load bitmaps so RT_BITMAP parameter is chosen
      returnVal:=EnumResourceNames(hMdl,RT_BITMAP,@Callback,0);
    

    @callback function returns a Boolean. You have to put this in the class level, before implementation code of the class. There's no declaration for it. My class is singleton so I call a class level procedure to add values to a TStringList. Do not return false if you have a more complex if statement and want to loop everything. If you return false at any time, calls to this function ends and you will not get rest of the resource names.

    function Callback(handle:THandle;ResType:PChar;ResName:Pchar;long:Lparam):bool;stdcall;
    var
          tempString: string;    
    begin  
          tempString := resname;
          if length(tempString) > 0 then begin
            MyClassName.AddToResourceNames(tempString);
            result := true;
          end else
            result := false;
    end;