How to embed an icon (.ico) in a static library (V

2020-06-25 13:23发布

问题:

Is there a way to embed resources (such as icons, dialogs) in a c++ (Win32 API) static library? My purpose is to embed an icon in the static library in a way that functions that use LoadIcon will work as if it was a normal .exe so the main application can only link to the static library and include a header file, with no requirement to add other files such as .rc files, or .ico files, etc. Clearly the main application who uses the static library doesn't have this resource so LoadIcon will fail, however I was wondering if there is a workaround to make it work. A static array with the icon data can work as long as the standard API calls (such as LoadIcon) will work.

To explain further, the person who will be using the static library will only have 2 files: .lib and .h and will not have any .rc file.

回答1:

I am posting an answer because after some research I found a way. Using my method, an icon can be used as an integral part of a static library and such library can be used by any type of application). See also: https://www.codeproject.com/Articles/1275122/How-to-embed-resources-in-a-Static-Library

  1. Icon is converted to a static array of BYTE. bin2c can be used for that.
  2. Data is converted into a HICON handle. Here is how I have done that:

    HICON GetIcon()
    { 
       DWORD dwTmp;
       int offset;
       HANDLE hFile;
       HICON hIcon = NULL;
       offset = LookupIconIdFromDirectoryEx(s_byIconData, TRUE, 0, 0, LR_DEFAULTCOLOR);
       if (offset != 0)
       {
          hIcon = CreateIconFromResourceEx(s_byIconData + offset, 0, TRUE, 0x00030000, 0, 0, LR_DEFAULTCOLOR | LR_DEFAULTSIZE);
       }
       return hIcon;  
    }
    
  3. GetIcon is used instead of LoadIcon. Instead of calling:

m_hIcon = ::LoadIcon(hInstanceIcon, MAKEINTRESOURCE(pXMB->nIcon));

I call

m_hIcon = GetIcon()