Pergunta

Existe alguma maneira de abrir um atalho do Windows (arquivo .lnk) e alterar seu destino? Encontrei o seguinte snippet que me permite encontrar o alvo atual, mas é uma propriedade somente leitura:

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;

Não consigo encontrar nada para alterar o alvo. Minha única opção é criar um novo atalho para substituir o atual? ..e se sim, como faço isso?

Foi útil?

Solução

Não é somente leitura, use o caminho lnk->, seguido por lnk-> save (). Supondo que você tenha privilégios de gravação para o arquivo. C# Código que faz a mesma coisa está na minha resposta em este tópico.

Outras dicas

Recriando um atalho com WSH

Você pode remover um atalho existente e criar um novo com o novo alvo. Para criar um novo, você pode usar o seguinte snippet:

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

No momento, não vejo nenhuma maneira de mudar o alvo sem recriar o atalho.

Nota: Para usar o trecho, você deve adicionar Modelo de objeto de host de script do Windows Com as referências do projeto.

Alterando o caminho alvo com shell32

Aqui está o trecho que muda o alvo de um atalho sem remover e recriá -lo:

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

O segundo é provavelmente o que você precisa.

Nota: Desculpe, os trechos estão em C#, pois não conheço C ++/CLI. Se alguém quiser reescrever esses trechos para C ++/CLI, fique à vontade para editar minha resposta.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top