Creare uno shortcut

 

La domanda del cliente pareva banale, ma ho faticato un po' a capire quale fosse la strada più agevole e con meno dipendenze per creare uno shortcut, così alla fine son arrivato a questo.

Nel progetto si aggiunge una reference alla libreria COM "Microsoft Shell Control And Automation" or direttamente a SHELL32.DLL.

 // startup shortcut
string linkDir = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
string linkFilename = "MyNotepad.lnk";
string linkPath = Path.Combine(linkDir, linkFilename);
// create dummy shortcut so getting the ShellLinkObject succeeds 
File.Create(linkPath).Close();
Shell shell = new ShellClass();
Folder folder = shell.NameSpace(linkDir);
FolderItem item = folder.Items().Item(linkFilename);
ShellLinkObject link = (ShellLinkObject)item.GetLink;
// now set shortcut properties as you like
string sysPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
string targetPath = Path.Combine(sysPath, "notepad.exe");
link.Path = targetPath;
link.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
link.Description = "My Notepad shortcut";
string iconPath = Path.Combine(sysPath, "moricons.dll");
link.SetIconLocation(iconPath, 1); link.Save(linkPath);
 

Ho impostato alcune proprietà giusto per divertimento.

Nello specifico ero interessato a far partire in modo automatico un programma al logon e l'uso dello shortcut non da' i problemi associati alle chiave di registry tipo la HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run. L'MSDN specifica infatti:

A program run from any of these keys should not write to the key during its execution.

mentre invece l'obiettivo è che il programma, una volta lanciato, controlli se è impostato per partire in modo automatico.

[Aggiornato il 19/11/2007: Corretta la formattazione così da rendere leggibile il codice]