Attaching a system imagelist to a list control

A system image list contains each file, folder, shortcut, etc. 's icon.  This can come  in very handy for creating a custom explore type application.  The first step consists of getting the small and large (if you want it) image lists from the system then attaching them to a CImageList and then adding them  to your list control.  Don't forget to Detach() them after you  are done or else all the icons on the system will disappear and a reboot seems to be the only fix.  Create the following member variables in you list control class:  CImageList m_smallImageList;  CImageList m_largeImageList;  And add this function:  void CSystemListCtrl::InitializeSystemImageList()  {   //image list setup   HIMAGELIST  hSystemSmallImageList, hSystemLargeImageList;   SHFILEINFO    ssfi, lsfi;     //get a handle to the system small icon list   hSystemSmallImageList =    (HIMAGELIST)SHGetFileInfo(    (LPCTSTR)_T("C:\\"),    0,    &ssfi,    sizeof(SHFILEINFO),    SHGFI_SYSICONINDEX | SHGFI_SMALLICON);  //attach it to the small image list  //--DON'T FORGET TO PUT m_smallImageList.Detach();  in your destructor   m_smallImageList.Attach(hSystemSmallImageList);    //do the same for the large   hSystemLargeImageList =    (HIMAGELIST)SHGetFileInfo(    (LPCTSTR)_T("C:\\"),    0,    &lsfi,    sizeof(SHFILEINFO),    SHGFI_SYSICONINDEX | SHGFI_ICON);   m_largeImageList.Attach(hSystemLargeImageList);    //Set the list control image list   SetImageList(&m_smallImageList, LVSIL_SMALL);   SetImageList(&m_largeImageList, LVSIL_NORMAL);  }
You will also need a function to get the image ID for each item you would like to dispaly
int CSystemListCtrl::GetIconIndex(const CString& csFileName)  //full path and file name
{               
        SHFILEINFO    sfi;

        SHGetFileInfo(
           (LPCTSTR)csFileName, 
           0,
           &sfi, 
           sizeof(SHFILEINFO), 
           SHGFI_SYSICONINDEX | SHGFI_SMALLICON );

        return sfi.iIcon;
}
Feed this result back into you ListCtrl LV_ITEM struct and you are on your way.
Note:  Windows 95/98 returns a full image list upfront where as NT4.0 only will retreive the icons as you ask for them in the future.

"If you do an imagecount on the imagelist right after you get the handle, you'll see the smaller imagelist.
Only until you iterate throught the various documents are they added to the NT imagelist." - Gil Rosin

Thanks to Robert Edward Caldecott and Gil Rosin for pointing this out!    


Copyright 2015 QuinStreet Inc. All Rights Reserved.