Search code examples
windowsdelphidelphi-10.3-rioshortcut-file

How find shortcut name by program name?


Is there some way to find the name of a shortcut (present on desktop) through the associated program name?

Ex:

Filename:

  • C:\Program Files\Mozilla Firefox\firefox.exe

and result in:

  • C:\Users\Public\Desktop\Firefox.lnk

I found something near to this, but is made the opposite way (returns the associated program name by shortcut name).


Solution

  • The application knows nothing about shortcuts that are created to point to it, so this isn't possible. You'd have to iterate every file in the user's Desktop folder looking for shortcut files, open them using IShellLink, and look to see if they launched the application you're looking to find. Here's an example of doing so. You'll need to add ShellAPI to your uses clause. FileName is the fully qualified name of the shortcut file.

    function GetLinkPath(const FileName: WideString): String;
    var
      ShellLink: IShellLink;
      Path: array[0..MAX_PATH] of Char;
    begin
      Result := '';
      ShellLink := CreateComObject(CLSID_ShellLink) as IShellLink;
      if (ShellLink as IPersistFile).Load(PWideChar(FileName), STGM_READ) = 0 then
      begin
        if ShellLink.GetPath(Path, MAX_PATH, nil, SLGP_SHORTPATH) = 0 then
          Result := Path;
      end;
    end;