Home Articles Books Downloads FAQs Tips

Q: Get the icon for a file or folder.

Answer: Displaying the icon for a file or folder is a simple, two step process. First, you obtain a handle for the system ImageList. Next, you pass a file or directory name to the API SHGetFileInfo function and ask it to return the corresponding index number for an icon in the system ImageList.

Step 1: Add a #include statement for the file SHELLAPI.H

    #include <win32\shellapi.h>

Step 2: Add an ImageList control to the main form of your program. Don't add any icons to the ImageList. Edit the constructor of the main form and add code to bind the ImageList control to the system ImageList. See the FAQ on how to display the same icons used by Windows for more documentation.

  SHFILEINFO info;
  DWORD ImageHandle = SHGetFileInfo("",
                                    0,
                                    &info,
                                    sizeof(info),
                                    SHGFI_ICON |
                                    SHGFI_SHELLICONSIZE |
                                    SHGFI_SYSICONINDEX);

  if (ImageHandle != 0)
  {
    ImageList1->Handle = ImageHandle;
    ImageList1->ShareImages = true;
  }

Step 3: Now add code that will return an icon index for the file, directory, or drive that you care about. Here are three examples:

  // This code fetches the icon for the C:\ drive
  SHFILEINFO info;
  DWORD result = SHGetFileInfo("C:\\",
                               0,
                               &info,
                               sizeof(info),
                               SHGFI_ICON |
                               SHGFI_SHELLICONSIZE |
                               SHGFI_SYSICONINDEX);

  // Check for failure. If return value was OK, the icon index
  // is return in the iIcon member of the SHFILEINFO structure.
  if(result != 0)
    ImageList1->GetIcon(info.iIcon,Image1->Picture->Icon);



  // This code fetches the icon for the C:\windows directory
  SHFILEINFO info;
  DWORD result = SHGetFileInfo("C:\\WINDOWS",
                               0,
                               &info,
                               sizeof(info),
                               SHGFI_ICON |
                               SHGFI_SHELLICONSIZE |
                               SHGFI_SYSICONINDEX);

  if(result != 0)
    ImageList1->GetIcon(info.iIcon,Image1->Picture->Icon);



  // This code fetches the icon for a text file
  SHFILEINFO info;
  DWORD result = SHGetFileInfo("C:\\CBUILDER\DEPLOY.TXT",
                               0,
                               &info,
                               sizeof(info),
                               SHGFI_ICON |
                               SHGFI_SHELLICONSIZE |
                               SHGFI_SYSICONINDEX);

  if(result != 0)
    ImageList1->GetIcon(info.iIcon,Image1->Picture->Icon);



Copyright © 1997-2000 by Harold Howe.
All rights reserved.