7

有什么方法可以打开 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;

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

4

2 回答 2

13

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

于 2010-09-29T16:05:08.013 回答
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();
}

目前,我没有看到任何方法可以在不重新创建快捷方式的情况下更改目标。

注意:要使用该片段,您必须将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();
}

第二个可能是您需要的。

注意:抱歉,由于我不了解 C++/CLI,因此这些片段是 C# 中的。如果有人想为 C++/CLI 重写这些片段,请随时编辑我的答案。

于 2010-09-29T15:31:07.210 回答