Retreive Custom Icon of a Disk in the Disk Drive

Post date: Mar 18, 2010 2:00:35 AM

Allows you to display the custom icon of the disk in the disk drive. One use for this would be a file manager.

function GetCDIcon(Drive: Char): TIcon;
var
  ico: TIcon;
  ini: TIniFile;
  s, p: string;
  i, j: Integer;
begin
  //Abort if "AutoRun.inf" doesn't exists.
  if FileExists(Drive + ':\autorun.inf') = False then Exit;
  //Opens the "AutoRun.inf"
  ini := TIniFile.Create(Drive + ':\autorun.inf');
  ico := TIcon.Create;
  try
    //Read the filename
    s := ini.ReadString('Autorun', 'ICON', '');
    //Abort if there is no icon specified
    if s = '' then Exit;
    //load the icon from a file
    if FileExists(s) then ico.LoadFromFile(s);
    if FileExists(Drive + ':\' + s) then ico.LoadFromFile(Drive + ':\' + s);
    //Load the icon from a Win32 resource
    if (FileExists(s) = False) and (FileExists(Drive + ':\' + s) = False) then 
    begin
      for j := (Pos(',', s) + 1) to Length(s) do 
      begin
        p := p + s[j];
      end;
      i := StrToInt(p);
      for j := Length(s) downto (Pos(',', s)) do
        Delete(s, j, Length(s));
      if FileExists(s) = False then s := Drive + ':\' + s;
      ico.Handle := ExtractIcon(hinstance, PChar(s), i);
    end;
    Result := ico;
  finally
    ini.Free;
  end;
end;