Home > Enterprise >  How can I get icon of Windows app in CPP?
How can I get icon of Windows app in CPP?

Time:04-04

I'm trying to build an File Manager with in Win32, and I have a problem with the icons. Whenever I trying to get icon that an windows 10 app is associated with it like .png (Photos app), the icon is blank paper. What I'm doing wrong? Thanks in advance and please answer :)

BOOL InitTreeViewImageLists(HWND hwndTV) {
    HIMAGELIST himl;  // handle to image list 
    HBITMAP hbmp;     // handle to bitmap 


    // Create the image list. 
    if ((himl = ImageList_Create(16,
        16,
        ILC_COLOR16 | ILC_MASK,
        3, 0)) == NULL)
        return FALSE;


    // Add the open file, closed file, and document bitmaps.
    HICON hIcon;
    SHFILEINFO sfi;
    LPCWSTR path = L"C:\\Users\\Shalev\\Desktop\\WhatsApp.lnk";
    sfi = GetShellInfo(path);
    HICON* iconHandles = new HICON;
    hIcon = sfi.hIcon;
    cout << hIcon << endl;
    g_nOpen = sfi.iIcon;
    ImageList_AddIcon(himl, hIcon);
    sfi = GetShellInfo(L"C:\\");
    hIcon = sfi.hIcon;
    g_nClosed = sfi.iIcon;
    ImageList_AddIcon(himl, hIcon);
    sfi = GetShellInfo(L"C:\\");
    hIcon = sfi.hIcon;
    g_nDocument = sfi.iIcon;
    ImageList_AddIcon(himl, hIcon);

    // Associate the image list with the tree-view control. 
    TreeView_SetImageList(hwndTV, himl, TVSIL_NORMAL);

    return TRUE;

}

SHFILEINFO GetShellInfo(LPCWSTR path) {
    SHFILEINFO sfi;
    SecureZeroMemory(&sfi, sizeof(sfi));
    SHGetFileInfo(path, 0, &sfi, sizeof(sfi), SHGFI_SYSICONINDEX | SHGFI_SHELLICONSIZE | SHGFI_ICON | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES);
    return sfi;
}

CodePudding user response:

You can use the IShellItemImageFactory interface, something like this:

...
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); // need this somewhere when your thread begins, not for every call
...
IShellItemImageFactory* factory;
if (SUCCEEDED(SHCreateItemFromParsingName(path, nullptr, IID_PPV_ARGS(&factory))))
{
    // the GetImage method defines a required size and multiple flags
    // with which you can specify you want the icon only or the thumbnail, etc.
    HBITMAP bmp;
    if (SUCCEEDED(factory->GetImage(SIZE{ 256, 256 }, SIIGBF_ICONONLY, &bmp)))
    {
        ... // do something with the HBITMAP
        DeleteObject(bmp);
    }
    factory->Release();
}

...
CoUninitialize(); // call this each time you successfully called CoInitializeEx
  • Related