How to get the data from a ShellLink even when the Link Target does not exist anymore?

天涯浪子 提交于 2019-12-04 05:39:22

问题


In Delphi XE7, I wanted to use the following code to replace the link target of a shell link file (.lnk), even when the link target does not exist anymore:

uses
  JclShell;
...
procedure ShellLinkReplaceLinkTarget(const AShellLinkFile, ANewTarget: string);
var
  ThisShellLink: JclShell.TShellLink;
begin
  if (JclShell.ShellLinkResolve(AShellLinkFile, ThisShellLink, SLR_ANY_MATCH or SLR_NO_UI) = S_OK) then
  begin
    ThisShellLink.Target := ANewTarget;
    JclShell.ShellLinkCreate(ThisShellLink, AShellLinkFile);
  end
    else CodeSite.Send('ShellLinkResolve Failed!');
end;

Obviously, it is not possible to get the data from the Link file with ShellLinkResolve when the link target does not exist anymore, as David kindly explained.

So how can I get the data from the link file in this case?


回答1:


Why don`t you want to use very simple code like this:

procedure ShellLinkReplaceLinkTarget(const AShellLinkFile, ANewTarget: UnicodeString);
var
  ShellLink: IShellLinkW;
  PersistFile: IPersistFile;
begin
  OleCheck(CoCreateInstance(CLSID_ShellLink, nil, CLSCTX_INPROC_SERVER, IShellLinkW, ShellLink));
  try
    OleCheck(ShellLink.QueryInterface(IPersistFile, PersistFile));
    try
      OleCheck(PersistFile.Load(PWideChar(AShellLinkFile), STGM_READWRITE));
      OleCheck(ShellLink.SetIDList(nil));
      OleCheck(ShellLink.SetPath(PWideChar(ANewTarget)));
      OleCheck(PersistFile.Save(PWideChar(AShellLinkFile), True));
    finally
      PersistFile := nil;
    end;
  finally
    ShellLink := nil;
  end;
end;

And there is one very important detail. Some lnk files can contain different properties like background color (in Windows 8). And if you recreate lnk file properties will be lost.



来源:https://stackoverflow.com/questions/29077977/how-to-get-the-data-from-a-shelllink-even-when-the-link-target-does-not-exist-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!