2008. január 22., kedd

Get the handle to the icon of a registered extension


Problem/Question/Abstract:

How can I get the icon of a registered extension (in the windows registry)?

Answer:

Solve 1:

First get the pointer to the operating systems image list and assign it to your own.

{Image List From System}
ImageListHandle := SHGetFileInfo('C:\', 0, FileInfo, SizeOf(FileInfo), SHGFI_SYSICONINDEX  or SHGFI_SMALLICON);
SendMessage(ListView1.Handle, LVM_SETIMAGELIST, LVSIL_SMALL, LParam(ImageListHandle));

Then in your listview you can extract out the icon by doing this:

function GetShellIcon(FileName: string; Folder: Boolean): Integer;
var
  FileInfo: TSHFileInfo;
  ImageHandle: THandle;
  Flag: Integer;
begin
  if Folder then
    Flag := FILE_ATTRIBUTE_DIRECTORY
  else
    Flag := FILE_ATTRIBUTE_NORMAL;
  SHGetFileInfo(PChar(FileName), Flag, FileInfo, SizeOf(FileInfo), SHGFI_SYSICONINDEX or SHGFI_SMALLICON or SHGFI_UseFileAttributes);
  Result := FileInfo.IIcon;
end;

Notice: At the bottom I assign the icon index from the IICON field of the data returned by SHGetFileInfo. So my function gets passed a filename and returns an image index. You could change the IICON field to the HICON field and then I believe you would be getting the handle to an icon.


Solve 2:

The SHGFI_SYSICONINDEX in the above code snippet is going to place the index of the icon in the system image list (a handle to which is being returned as the result of the SHGetFileInfo function call) in the FileInfo.iIcon member. Use the SHGFI_ICON flag instead to get an icon handle in HIcon.

function GetShellIcon(FileName: string; Folder: Boolean): Integer;
var
  FileInfo: TSHFileInfo;
  ImageHandle: THandle;
  Flag: Integer;
  IconHandle: THandle;
begin
  if Folder then
    Flag := FILE_ATTRIBUTE_DIRECTORY
  else
    Flag := FILE_ATTRIBUTE_NORMAL;
  SHGetFileInfo(PChar(FileName), Flag, FileInfo, SizeOf(FileInfo),
    SHGFI_ICON or SHGFI_SMALLICON or SHGFI_UseFileAttributes);
  Result := FileInfo.IIcon;
  IconHandle := FileInfo.HIcon;
end;


Solve 3:

One method of getting the associated icon with a particular file is to first populate an imagelist with registered system icons (this example is for small icons, you could do the same for large). In this example, iIndex will be the ImageList item for the particular file.

var
  dwSmallIcon: DWord;
  pFileInfo: TshFileInfo;
  iIndex: Integer;
begin
  dwSmallIcon := SHGetFileInfo('', 0, FileInfo, SizeOf(TshFileInfo), (SHGFI_ICON or
    SHGFI_SMALLICON or SHGFI_SYSICONINDEX));
  ImageList1.Handle := dwSmallIcon; {imagelist}
  ImageList1.ShareImages := True;
  FillChar(pFileInfo, SizeOf(TshFileInfo), 0);
  shGetFileInfo(pName, 0, pFileInfo, SizeOf(TshFileInfo), SHGFI_SYSICONINDEX or
    SHGFI_SMALLICON or SHGFI_OPENICON);
  iIndex := pFileInfo.iIcon;
end;

Nincsenek megjegyzések:

Megjegyzés küldése