Tuesday, March 6, 2012

Load Explorer file extension icon in Win32

When programming with C and Win32, sometimes you need to load an icon, as displayed on Windows Explorer, relative to a file extension. For example, you need to load the Explorer icon associated to the “txt” file extension.

Here is a quick function I use to do it:
HICON ExplorerIcon(const wchar_t *fileExtension)
{
	wchar_t extens[10];
	SHFILEINFO shfi = { 0 };

	lstrcpy(extens, L"*.");
	lstrcat(extens, fileExtension);
	SHGetFileInfo(extens, FILE_ATTRIBUTE_NORMAL, &shfi, sizeof(shfi),
		SHGFI_TYPENAME | SHGFI_USEFILEATTRIBUTES);
	SHGetFileInfo(extens, FILE_ATTRIBUTE_NORMAL, &shfi, sizeof(shfi),
		SHGFI_ICON | SHGFI_SMALLICON | SHGFI_SYSICONINDEX | SHGFI_USEFILEATTRIBUTES);

	return shfi.hIcon; // use DestroyIcon() on this handle
}

// Usage example:
HICON hIconTxt = ExplorerIcon(L"txt");
Remember to release the HICON handle by calling DestroyIcon after using it, or you’ll have a resource leak.

No comments: