Shell API
You can get them from the shell by calling SHGetFileInfo()
along with the SHGFI_USEFILEATTRIBUTES
flag - this flag allows the routine to work without requiring the filename passed in to actually exist, so if you have a file extension just make up a filename, append the extension, and pass it in.
By combining other flags, you'll be able to retrieve:
- A large or small icon as determined by the system configuration:
SHGFI_ICON|SHGFI_LARGEICON
or SHGFI_ICON|SHGFI_SMALLICON
- A large or small icon as determined by the shell configuration:
SHGFI_ICON|SHGFI_LARGEICON|SHGFI_SHELLICONSIZE
or SHGFI_ICON|SHGFI_SMALLICON|SHGFI_SHELLICONSIZE
- The index of the icon in the shell's image list along with the appropriate image list:
SHGFI_SYSICONINDEX
- The path and filename of the actual module where the icon is stored (along with the icon index in that module):
SHGFI_ICONLOCATION
Examples
// Load a System Large icon image
SHGetFileInfo( szFileName, FILE_ATTRIBUTE_NORMAL, &shfi, sizeof(SHFILEINFO),
SHGFI_USEFILEATTRIBUTES | SHGFI_ICON | SHGFI_LARGEICON);
// Load a System Small icon image
SHGetFileInfo( szFileName, FILE_ATTRIBUTE_NORMAL, &shfi, sizeof(SHFILEINFO),
SHGFI_USEFILEATTRIBUTES | SHGFI_ICON | SHGFI_SMALLICON);
// Load a Shell Large icon image
SHGetFileInfo( szFileName, FILE_ATTRIBUTE_NORMAL, &shfi, sizeof(SHFILEINFO),
SHGFI_USEFILEATTRIBUTES | SHGFI_ICON | SHGFI_SHELLICONSIZE);
// Load a Shell Small icon image
SHGetFileInfo( szFileName, FILE_ATTRIBUTE_NORMAL, &shfi, sizeof(SHFILEINFO),
SHGFI_USEFILEATTRIBUTES
| SHGFI_ICON | SHGFI_SHELLICONSIZE | SHGFI_SMALLICON);
If you want to draw such an icon, use something like this:
// Draw it at its native size
DrawIconEx( hDC, nLeft, nTop, hIcon, 0, 0, 0, NULL, DI_NORMAL );
// Draw it at the System Large size
DrawIconEx( hDC, nLeft, nTop, hIcon, 0, 0, 0,
NULL, DI_DEFAULTSIZE | DI_NORMAL );
// Draw it at some other size (40x40 in this example)
DrawIconEx( hDC, nLeft, nTop, hIcon, 40, 40, 0, NULL, DI_NORMAL );
The icon handle as well as the file system path can be obtained from the SHFILEINFO
structure:
typedef struct _SHFILEINFOA
{
HICON hIcon; // out: icon
int iIcon; // out: icon index
DWORD dwAttributes; // out: SFGAO_ flags
CHAR szDisplayName[MAX_PATH]; // out: display name (or path)
CHAR szTypeName[80]; // out: type name
} SHFILEINFOA;
Keep in mind that you must free the obtained icon by passing hIcon
to DestroyIcon()
after you're done with it.