问题
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