How to get the icon of a file?

3 06 2008

If you try to delete files in Vista, you can see the following dialog.

Did you noticed that, for every file, it will display its corresponding file icon. That’s pretty nice thing. If you are writing your own file browser tree or list, it will be nice to display the files with their own icons. But how can you get the file icon of a file?

You can use the call – SHGetFileInfo(). While calling the function, pass SHGFI_ICON as parameter. It will return handle for File icon. See the following code snippet.

// The classic FooBar. ;)
CString FilePath = _T("C:\\");

// Get the file icon.
SHFILEINFO FileInfo = { 0 };
SHGetFileInfo( FilePath,
               sizeof( FileInfo ),
               SHGFI_ICON );

// FileInfo.hIcon contains Icon handle.

There are more constants such as – SHGFI_ICONLOCATION, SHGFI_LARGEICON, SHGFI_SMALLICON etc. Seems they are self explanatory. 😉

Targeted Audience – Intermediate.