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

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 Script Host ObjectModelCOMをプロジェクト参照に追加する必要があります。

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();
}

2つ目はおそらくあなたが必要とするものです。

注:申し訳ありませんが、C ++ / CLIがわからないため、スニペットはC#になっています。誰かがC++/ CLI用にこれらのスニペットを書き直したい場合は、私の答えを自由に編集してください。

于 2010-09-29T15:31:07.210 に答える
13

読み取り専用ではありません。代わりにlnk->Pathを使用し、続いてlnk-> Save()を使用してください。ファイルへの書き込み権限があると仮定します。同じことを行うC#コードは、このスレッドの私の答えにあります。

于 2010-09-29T16:05:08.013 に答える