Board index » delphi » how to get Icon associated with an extension

how to get Icon associated with an extension

I need to get the Icon that windows associates with a given extension.
Yes, I know I can use ExtractAssociatedIcon - but that only works if the
file exists on the disk.

I will know the file name, but the file itself doesn't exist on the hard
disk at the time I need to get the Icon for its extension.  Is there a
way to get the Icon associated with the extension?

Thanks,
Glenn

 

Re:how to get Icon associated with an extension


Hey Glenn,

Probably the best way to get the associated Icon is to get the system image
list which contains all of the associated icons.  Here's how you do that...

procedure TForm1.FormCreate(Sender: TObject)
var
SysIL: HImageList;
SFI: TSHFileINfo;
begin
SysIL := SHGetFileInfo('', 0, SFI, SizeOF(SFI), SHGFI_SYSICONINDEX or
SHGFI_SMALLICON); {SHGFI_LARGEICON for large icons}
if SysIL <> 0 then
   ImagelistSmall.Handle := SysIL;
end;

ImagelistSmall is just an TImageList component.  Make sure that you set the
shareImage property to true or you'll get some really interesting behavior
when your system image list is freed up on program exit.

The next step is to get the imageIndex associated with a file extension.
Here's how you do that.

function TForm1.GetIconIndex(const AFile: String; Attrs: DWORD):Integer;
var
SFI: TSHFileInfo;
begin
   SHGetFileInfo(PChar(AFile), Attrs, SFI, SizeOf(TSHFileInfo),
       SHGFI_SYSICONINDEX or SHGFI_USEFILEATTRIBUTES);
   Result := SFI.iIcon;
end;

Access it with:
GetIconIndex(FileName, FILE_ATTRIBUTE_NORMAL);

I can't remember what the Attrs variable does, It's been a while.
Oh yeah, You'll need the correct stuff in your uses clause.

I think you need shlobj, wintypes, commctrl (but I'm not completely sure)

Hope that helps,
Dean Liske (TECSKOR)

Quote
gglo...@pcisys.net wrote in message <358B9DF5.3...@pcisys.net>...
>I need to get the Icon that windows associates with a given extension.
>Yes, I know I can use ExtractAssociatedIcon - but that only works if the
>file exists on the disk.

>I will know the file name, but the file itself doesn't exist on the hard
>disk at the time I need to get the Icon for its extension.  Is there a
>way to get the Icon associated with the extension?

>Thanks,
>Glenn

Re:how to get Icon associated with an extension


Quote
Dean Liske wrote:

> Hey Glenn,

> Probably the best way to get the associated Icon is to get the system image
> list which contains all of the associated icons.  Here's how you do that...

Wow, thanks.  and only an hour and a half after I posted the question
...

You're a lifesaver

Glenn

Other Threads