从可执行文件中获取小图标或大图标

时间:2017-10-14 19:47:21

标签: delphi icons delphi-10.1-berlin

在Delphi 10.1.2 Berlin中,我需要使用特定的IconIndex从.EXE文件中提取LARGE图标(32x32)或SMALL图标(16x16):

function GetIconFromExecutableFile(const AFileName: string; const Large: Boolean; const AIconIndex: Integer): TIcon;
var
  Icon: HICON;
  ExtractedIconCount: UINT;
  ThisIconIdx: Integer;
  F: string; 
begin
  Result := nil;
  try
    ThisIconIdx := AIconIndex;

    F := AFileName;
    if Large then
    begin
      // error on nil: [dcc32 Error]: E2033 Types of actual and formal var parameters must be identical
      ExtractedIconCount := ExtractIconEx(PChar(F), ThisIconIdx, Icon, nil, 1);
    end
    else
    begin
      // error on nil: [dcc32 Error]: E2033 Types of actual and formal var parameters must be identical
      ExtractedIconCount := ExtractIconEx(PChar(F), ThisIconIdx, nil, Icon, 1);
    end;

    Win32Check(ExtractedIconCount = 1);

    Result := TIcon.Create;
    Result.Handle := Icon;
  except
    Result.Free;
    raise;
  end;
end;

对排除的图标大小使用nil会产生编译错误。

那么我怎样才能获得所需的图标?

1 个答案:

答案 0 :(得分:1)

一种方法是修复API函数的声明:

type
  PHICON = ^HICON;
function ExtractIconEx(lpszFile: LPCWSTR; nIconIndex: int; phiconLarge, phiconSmall: PHICON; nIcons: UINT): UINT; stdcall; external shell32 name 'ExtractIconExW' delayed;

然后使用:

procedure TForm1.FormCreate(Sender: TObject);
var
  Icon : HICON;
begin
  if ExtractIconEx(Pchar(ParamStr(0)), 0, @Icon, nil, 1) = 1 then begin
    self.Icon.Handle := Icon;
    DestroyIcon(Icon);
  end;