2008-10-24 12 views
67

¿Cómo se crea un acceso directo a la aplicación (archivo .lnk) en C# o usando .NET framework?Crear acceso directo a la aplicación en un directorio

El resultado sería un archivo .lnk a la aplicación o URL especificada.

+0

Esto podría ser útil: http://www.codeproject.com/Articles/3905/Creating-Shell-Links-Shortcuts-in-NET-Programs-Usi –

Respuesta

61

No es tan simple como me hubiera gustado, pero hay una gran llamada clase ShellLink.cs en vbAccelerator

Este código utiliza interoperabilidad, pero no se basa en WSH.

El uso de esta clase, el código para crear el acceso directo es:

private static void configStep_addShortcutToStartupGroup() 
{ 
    using (ShellLink shortcut = new ShellLink()) 
    { 
     shortcut.Target = Application.ExecutablePath; 
     shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath); 
     shortcut.Description = "My Shorcut Name Here"; 
     shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal; 
     shortcut.Save(STARTUP_SHORTCUT_FILEPATH); 
    } 
} 
+0

¿Alguien probó ShellLink en Vista? Parece que el código fue escrito en 2003. – blak3r

+0

Funcionó en Windows Server 2008 Standard 64bit SP2. No veo ninguna razón por la que no lo haría en Vista. –

+9

Funciona en Windows 7 e incluso en aplicaciones de 64 bits :) – fparadis2

14

he encontrado algo como esto:

private void appShortcutToDesktop(string linkName) 
{ 
    string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); 

    using (StreamWriter writer = new StreamWriter(deskDir + "\\" + linkName + ".url")) 
    { 
     string app = System.Reflection.Assembly.GetExecutingAssembly().Location; 
     writer.WriteLine("[InternetShortcut]"); 
     writer.WriteLine("URL=file:///" + app); 
     writer.WriteLine("IconIndex=0"); 
     string icon = app.Replace('\\', '/'); 
     writer.WriteLine("IconFile=" + icon); 
     writer.Flush(); 
    } 
} 

Código original en sorrowman's article "url-link-to-desktop"

+12

Dada la elección entre interoperabilidad/wsh o ingeniería inversa del formato de archivo, elegiría este último. Creo que es una apuesta bastante segura que no cambiarán el formato pronto. – chrisortman

+18

Anuraj: Estás haciendo trampa: esto no crea un LNK sino un archivo URL. –

+0

@HelgeKlein Está bien si [registró su aplicación para usar un esquema URI] (http://msdn.microsoft.com/en-us/library/aa767914 (VS.85) .aspx) –

46

agradable y limpio. (.NET 4,0)

Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8")); //Windows Script Host Shell Object 
dynamic shell = Activator.CreateInstance(t); 
try{ 
    var lnk = shell.CreateShortcut("sc.lnk"); 
    try{ 
     lnk.TargetPath = @"C:\something"; 
     lnk.IconLocation = "shell32.dll, 1"; 
     lnk.Save(); 
    }finally{ 
     Marshal.FinalReleaseComObject(lnk); 
    } 
}finally{ 
    Marshal.FinalReleaseComObject(shell); 
} 

Eso es todo, no hay código adicional necesario. CreateShortcut incluso puede cargar accesos directos desde el archivo, por lo que propiedades como TargetPath devuelven información existente. Shortcut object properties.

También es posible de esta manera para versiones de tipos dinámicos que no admitan .NET. (.NET 3,5)

Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8")); //Windows Script Host Shell Object 
object shell = Activator.CreateInstance(t); 
try{ 
    object lnk = t.InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, shell, new object[]{"sc.lnk"}); 
    try{ 
     t.InvokeMember("TargetPath", BindingFlags.SetProperty, null, lnk, new object[]{@"C:\whatever"}); 
     t.InvokeMember("IconLocation", BindingFlags.SetProperty, null, lnk, new object[]{"shell32.dll, 5"}); 
     t.InvokeMember("Save", BindingFlags.InvokeMethod, null, lnk, null); 
    }finally{ 
     Marshal.FinalReleaseComObject(lnk); 
    } 
}finally{ 
    Marshal.FinalReleaseComObject(shell); 
} 
+1

Muy limpio. Esta sería la respuesta principal si la pregunta se hiciera nuevamente. – Damien

+0

Esto no podrá crear un acceso directo cuyo nombre tenga caracteres Unicode. Probado en Win7 con .NET 4.0. El objeto COM reemplaza los caracteres Unicode con signos de interrogación, que no son válidos en un nombre de archivo. –

+0

No es gran cosa, puede cambiar el nombre del archivo después de '.Guardar' de todos modos, pero gracias por notificar. – IllidanS4

1

Donwload IWshRuntimeLibrary

También es necesario importar de biblioteca COM IWshRuntimeLibrary. Haga clic derecho en su proyecto -> agregar referencia -> COM -> IWshRuntimeLibrary -> agregar y luego use el siguiente fragmento de código.

private void createShortcutOnDesktop(String executablePath) 
{ 
    // Create a new instance of WshShellClass 

    WshShell lib = new WshShellClass(); 
    // Create the shortcut 

    IWshRuntimeLibrary.IWshShortcut MyShortcut; 


    // Choose the path for the shortcut 
    string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); 
    MyShortcut = (IWshRuntimeLibrary.IWshShortcut)lib.CreateShortcut(@deskDir+"\\AZ.lnk"); 


    // Where the shortcut should point to 

    //MyShortcut.TargetPath = Application.ExecutablePath; 
    MyShortcut.TargetPath = @executablePath; 


    // Description for the shortcut 

    MyShortcut.Description = "Launch AZ Client"; 

    StreamWriter writer = new StreamWriter(@"D:\AZ\logo.ico"); 
    Properties.Resources.system.Save(writer.BaseStream); 
    writer.Flush(); 
    writer.Close(); 
    // Location for the shortcut's icon   

    MyShortcut.IconLocation = @"D:\AZ\logo.ico"; 


    // Create the shortcut at the given path 

    MyShortcut.Save(); 

} 
+0

No tengo esa biblioteca COM en mi PC con Windows 8. – Damien

+0

@Damien Hay algo llamado Google ... lolx: D, bromeo, querida, puedes descargarlo desde aquí. También estoy actualizando mi pregunta. Gracias por señalarlo http://originaldll.com/file/interop.iwshruntimelibrary.dll/20842.html –

1

Después de examinar todas las posibilidades que encontré en SO me he decidido por ShellLink:

//Create new shortcut 
using (var shellShortcut = new ShellShortcut(newShortcutPath) 
{ 
    Path = path 
    WorkingDirectory = workingDir, 
    Arguments = args, 
    IconPath = iconPath, 
    IconIndex = iconIndex, 
    Description = description, 
}) 
{ 
    shellShortcut.Save(); 
} 

//Read existing shortcut 
using (var shellShortcut = new ShellShortcut(existingShortcut)) 
{ 
    path = shellShortcut.Path; 
    args = shellShortcut.Arguments; 
    workingDir = shellShortcut.WorkingDirectory; 
    ... 
} 

Aparte de ser simple y eficaz, el autor (Mattias Sjögren, MS MVP) es una especie de COM/PInvoke/Interop guru, y leyendo detenidamente su código, creo que es más sólido que las alternativas.

Cabe mencionar que los archivos de acceso directo también pueden ser creados por varias utilidades de línea de comandos (que a su vez pueden invocarse fácilmente desde C# /. NET). Nunca intenté con ninguno de ellos, pero comenzaría con NirCmd (NirSoft tiene herramientas de calidad similares a SysInternals).

Desafortunadamente no NirCmd puede analizar archivos de acceso directo (sólo crearlos), pero para ese propósito TZWorks lp parece capaz. Incluso puede formatear su salida como csv. lnk-parser también se ve bien (puede generar tanto HTML como CSV).

+1

. Algo irónico, dado que el enlace contiene el texto "webhost4life", pero ese enlace de ShellLink es 404 :-( – noonand

+0

@no y de hecho, y parece que la biblioteca tampoco fue almacenada en la Wayback Machine. Afortunadamente he conservado una copia: https://onedrive.live.com/redir?resid=DED6DB63D5309C3D!98150&authkey=!AFaK2w3dATW3U7E&ithint=file%2czip –

1

Similar a IllidanS4's answer, usando el Windows Script Host demostró ser la solución más fácil para mí (probado en Windows 8 de 64 bits).

Sin embargo, en lugar de importar el tipo COM manualmente a través del código, es más fácil simplemente agregar la biblioteca de tipo COM como referencia. Elija References->Add Reference..., COM->Type Libraries y busque y agregue "Windows Script Host Object Model".

Esto importa el espacio de nombres IWshRuntimeLibrary, desde donde se puede acceder a:

WshShell shell = new WshShell(); 
IWshShortcut link = (IWshShortcut)shell.CreateShortcut(LinkPathName); 
link.TargetPath=TargetPathName; 
link.Save(); 

Credit goes to Jim Hollenhorst.

Cuestiones relacionadas