delphi 获取文件图标

{根据文件的名字得到此文件在系统中对应大小的图标large=true(64*64) false(32*32)}
procedure GetFileIcon(TypeName: Widestring; Icon: TIcon;Large:Boolean=False);
var
strTmp: Widestring;
IndexS, IndexL: HIcon;
ShFileInfo: TSHFileInfo ;
imgList: TImageList;
begin
strTmp := TypeName;
TypeName := Tnt_WideLowerCase(wideExtractFileExt(strTmp));
if pos('.', TypeName) = 0 then
TypeName := '.' + TypeName;
if Large then
begin
//如果是EXE、Ico文件,直接取文件的图标
if (TypeName = '.exe') or (TypeName = '.ico') then
begin
ExtractIconExw(pwidechar(strTmp), 0, IndexL, IndexS, 1);
if IndexS <> 0 then
begin
Icon.Handle := IndexL;
exit;
end;
end;
//在临时目录下建立一个空类型文件,便于取图标
TypeName := GetWindowsTempPath + TypeName;
if not wideFileExists(TypeName) then
with TUniFileStream.Create(TypeName, fmCreate) do
Free;
imgList := TImageList.CreateSize(64, 64);
try
{将系统图象列表连接到TListView控件上。注意我们设置动态建立的图象列表
的ShareImages属性为真,这可以确保我们不试图释放Windows系统拥有的图象}
imgList.ShareImages := True;
imgList.Handle := ShGetFileInfo ('', 0, SHFileInfo, SizeOf(SHFileInfo),
SHGFI_SYSICONINDEX or
SHGFI_LARGEICON);
ShGetFileInfo (pchar( string( TypeName)), 0, SHFileInfo, SizeOf(SHFileInfo),
SHGFI_SYSICONINDEX or
SHGFI_LARGEICON);
imgList.GetIcon(SHFileInfo.iIcon, Icon);
finally
imgList.Free;
end;
end else
begin
//如果是EXE、Ico文件,直接取文件的图标
if (TypeName = '.exe') or (TypeName = '.ico') then
begin
ExtractIconExw(pwidechar(strTmp), 0, IndexL, IndexS, 1);
if IndexS <> 0 then
begin
Icon.Handle := IndexS;
exit;
end;
end;
//在临时目录下建立一个空类型文件,便于取图标
TypeName := GetWindowsTempPath + TypeName;
if not wideFileExists(TypeName) then
with TUniFileStream.Create(TypeName, fmCreate) do
Free;
imgList := TImageList.CreateSize(32, 32);
try
imgList.ShareImages := True;
imgList.Handle := ShGetFileInfo ('', 0, SHFileInfo, SizeOf(SHFileInfo),
SHGFI_SYSICONINDEX or
SHGFI_SMALLICON);
ShGetFileInfo (pchar( string( TypeName)), 0, SHFileInfo, SizeOf(SHFileInfo),
SHGFI_SYSICONINDEX or
SHGFI_SMALLICON);
imgList.GetIcon(SHFileInfo.iIcon, Icon);
finally
imgList.Free;
end;
end;
end;

原文地址:https://www.cnblogs.com/blogpro/p/11446769.html