How to create a file shortcut (*.lnk file) on desktop in Windows?

前端 未结 3 2211
清歌不尽
清歌不尽 2021-02-08 03:39
function GetDesktopFolder: string;
var
  buf: array[0..MAX_PATH] of Char;
  pidList: PItemIDList;
begin
  Result := StrNoDesktopFolderFo;
  SHGetSpecialFolderLocation(Ap         


        
3条回答
  •  有刺的猬
    2021-02-08 04:10

    I would do it e.g. this way

    uses
      ShlObj, ComObj, ActiveX;
    
    function GetDesktopFolder: string;
    var
      PIDList: PItemIDList;
      Buffer: array [0..MAX_PATH-1] of Char;
    begin
      Result := '';
      SHGetSpecialFolderLocation(Application.Handle, CSIDL_DESKTOP, PIDList);
      if Assigned(PIDList) then
        if SHGetPathFromIDList(PIDList, Buffer) then
          Result := Buffer;
    end;
    
    function CreateDesktopShellLink(const TargetName: string): Boolean;
    var
      IObject: IUnknown;
      ISLink: IShellLink;
      IPFile: IPersistFile;
      PIDL: PItemIDList;
      LinkName: string;
      InFolder: array [0..MAX_PATH-1] of Char;
    begin
      Result := False;
    
      IObject := CreateComObject(CLSID_ShellLink);
      ISLink := IObject as IShellLink;
      IPFile := IObject as IPersistFile;
    
      with ISLink do
      begin
        SetDescription('Description ...');
        SetPath(PChar(TargetName));
        SetWorkingDirectory(PChar(ExtractFilePath(TargetName)));
      end;
    
      SHGetSpecialFolderLocation(0, CSIDL_DESKTOPDIRECTORY, PIDL);
      SHGetPathFromIDList(PIDL, InFolder) ;
    
      LinkName := IncludeTrailingBackslash(GetDesktopFolder);
      LinkName := LinkName + ExtractFileName(TargetName) + '.lnk';
    
      if not FileExists(LinkName) then
        if IPFile.Save(PWideChar(LinkName), False) = S_OK then
          Result := True;
    end;
    
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      if CreateDesktopShellLink('C:\Folder\ExeFile.exe') then
        ShowMessage('Link has been created ...');
    end;
    

提交回复
热议问题