如何以编程方式更改.lnk以更改其目标?

Jon*_*age 6 .net shell32 c++-cli windows-xp-embedded

有没有办法打开Windows快捷方式(.lnk文件)并更改它的目标?我找到了以下代码片段,它允许我找到当前目标,但它是一个只读属性:

Shell32::Shell^ shl = gcnew Shell32::Shell();
String^ shortcutPos = "C:\\some\\path\\to\\my\\link.lnk";
String^ lnkPath = System::IO::Path::GetFullPath(shortcutPos);
Shell32::Folder^ dir = shl->NameSpace(System::IO::Path::GetDirectoryName(lnkPath));
Shell32::FolderItem^ itm = dir->Items()->Item(System::IO::Path::GetFileName(lnkPath));
Shell32::ShellLinkObject^ lnk = (Shell32::ShellLinkObject^)itm->GetLink;
String^ target = lnk->Target->Path;
Run Code Online (Sandbox Code Playgroud)

我找不到任何改变目标的东西.我唯一的选择是创建一个新的快捷方式来覆盖当前的快捷方式吗?..如果是的话,我该怎么做?

Ars*_*nko 13

使用WSH重新创建快捷方式

您可以删除现有快捷方式并使用新目标创建新快捷方式.要创建新代码,您可以使用以下代码段:

public void CreateLink(string shortcutFullPath, string target)
{
    WshShell wshShell = new WshShell();
    IWshRuntimeLibrary.IWshShortcut newShortcut = (IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(shortcutFullPath);
    newShortcut.TargetPath = target;
    newShortcut.Save();
}
Run Code Online (Sandbox Code Playgroud)

目前,我没有看到任何方法来更改目标而不重新创建快捷方式.

注意:要使用该代码段,必须将Windows脚本宿主对象模型 COM添加到项目引用中.

使用Shell32更改目标路径

这是更改快捷方式目标而不删除并重新创建它的代码段:

public void ChangeLinkTarget(string shortcutFullPath, string newTarget)
{
    // Load the shortcut.
    Shell32.Shell shell = new Shell32.Shell();
    Shell32.Folder folder = shell.NameSpace(Path.GetDirectoryName(shortcutFullPath));
    Shell32.FolderItem folderItem = folder.Items().Item(Path.GetFileName(shortcutFullPath));
    Shell32.ShellLinkObject currentLink = (Shell32.ShellLinkObject)folderItem.GetLink;

    // Assign the new path here. This value is not read-only.
    currentLink.Path = newTarget;

    // Save the link to commit the changes.
    currentLink.Save();
}
Run Code Online (Sandbox Code Playgroud)

第二个可能是你需要的.

注意:抱歉,这些片段在C#中,因为我不知道C++/CLI.如果有人想要为C++/CLI重写这些片段,请随时编辑我的答案.

  • 有关如何引用 Shell32 的信息,请参阅[此处](/sf/answers/1322630431/) (2认同)

Han*_*ant 13

它不是只读的,而是使用lnk-> Path,然后使用lnk-> Save().假设您对该文件具有写权限.做同样的事情C#代码是我在回答这个线程.