Mega Code Archive

 
Categories / Delphi / Files
 

Getting the associated Icon of any file

Title: Getting the associated Icon of any file Question: This article shows you how to extract the associated icon of any file. Including files that use shell icon handlers such as ICO and Corel Draw files. Answer: Just a few days ago, I published an article on creating an shell icon handler allowing you to manually create icons for every file of a specific file type. This article shows you how to get such icons without much work. Using the function SHGetFileInfo from the ShellAPI unit it is a rather simple task. This article will simply provide you with the steps you have to take in order to get the icon. Starting with creating a new application drop a PaintBox, a Button and a OpenDialog on the form. Fill the Button OnClick with the following procedure: procedure TForm1.Button1Click(Sender: TObject); begin if OpenDialog1.Execute then DrawFile(OpenDialog1.FileName); end; Next you need the DrawFile method. The lines are commented. procedure TForm1.DrawFile(Name: String); var FileInfo: TSHFileInfo; ImageListHandle: THandle; aIcon: TIcon; begin // clear the memory FillChar(FileInfo, SizeOf(FileInfo), #0); // get a handle to the ImageList for the file selected ImageListHandle := SHGetFileInfo( PChar(Name), 0, FileInfo, SizeOf(FileInfo), // we want an icon in LARGE SHGFI_ICON or SHGFI_LARGEICON ); try // create a icon class aIcon := TIcon.Create; try // assign the handle of the icon returned aIcon.Handle := FileInfo.hIcon; // lets paint it transparent aIcon.Transparent := True; with PaintBox1 do begin // resize the paint box to icon size Width := aIcon.Width; Height := aIcon.Height; // tell our app to first resize the paint box before we draw the icon Application.ProcessMessages; // clear the paintbox Canvas.Rectangle(-1, -1, Succ(Width), Succ(Height)); // copy the icon Canvas.Draw(0, 0, aIcon); end; finally // free our icon class FreeAndNil(aIcon); end; finally // !!! FREE THE ICON PROVIDED BY THE SHELL DestroyIcon(FileInfo.hIcon); // free the image list handle ImageList_Destroy(ImageListHandle); end; end; I hope this will help you. Daniel Wischnewski.