取得文件图标并在TListView中显示

技术要点:  一、使用SHGetFileInfo函数获取指定扩展名的文件图标。需要引用ShellAPI单元。  二、使用TStringList来保存扩展名与其图标的索引号。当添加一个文件名至TListView后,我们已经取得了其图标,再次添加同样扩展名的文件时,不需再次获取其图标,只要从该TStringList中取得其图标索引号即可。 uses ShellAPI; var IconList:TStringList; { 实现获取图标及将图标添加到TImageList中的过程 } procedure ListView_SetItemImageIndex(Item: TListItem); var nIndex:Integer; Icon:TIcon; fileName:string; extName:string; sinfo:SHFILEINFO; begin if TListView(Item.ListView).SmallImages<>nil then begin fileName:=Item.Caption; extName:=ExtractFileExt(fileName); nIndex:=IconList.IndexOf(extName); if nIndex>-1 then begin nIndex:=Integer(IconList.Objects[nIndex]); Item.ImageIndex:=nIndex; end else begin FillChar(sinfo, SizeOf(sinfo),0); SHGetFileInfo(PChar(extName),FILE_ATTRIBUTE_NORMAL,sinfo,SizeOf(sInfo),SHGFI_USEFILEATTRIBUTES or SHGFI_ICON or SHGFI_SMALLICON); if sinfo.hIcon>0 then begin Icon:=TIcon.Create; Icon.Handle:=sinfo.hIcon; nIndex:=TListView(Item.ListView).SmallImages.AddIcon(Icon); Icon.Free; Item.ImageIndex:=nIndex; IconList.AddObject(extName,TObject(nIndex)); end; end; end; end; { 测试过程 } procedure TForm1.Button1Click(Sender: TObject); var Item:TListItem; begin Item:=ListView1.Items.Add; Item.Caption:='c:\test.jpg'; ListView_SetItemImageIndex(Item); end; { 对IconList进行初始化及释放 } initialization IconList:=TStringList.Create; finalization IconList.Free; end.

posted @ 2010-08-25 23:28  覆雨翻云  阅读(382)  评论(0编辑  收藏  举报