Pregunta

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

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

¿Fue útil?

Solución

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

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

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

Otros consejos

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 se necesita código adicional. CreateShortcut incluso puede cargar accesos directos desde archivos, por lo que propiedades como TargetPath devuelven información existente. Propiedades del objeto de acceso directo .

También es posible de esta manera para versiones de .NET que no admiten tipos dinámicos. ( .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);
}

Encontré 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 artículo de Sorrowman " url-link -to-escritorio "

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;
    ...
}

Además de ser simple y efectivo, el autor (Mattias Sj & # 246; gren, MS MVP) es una especie de gurú de COM / Pvoca / Interoperabilidad, y al leer su código creo que es más robusto que las alternativas. p>

Debe mencionarse que los archivos de acceso directo también pueden crearse mediante varias utilidades de línea de comandos (que a su vez pueden invocarse fácilmente desde C # / .NET). Nunca probé ninguno de ellos, pero comenzaría con NirCmd (NirSoft tiene SysInternals- como herramientas de calidad).

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

Similar a La respuesta de IllidanS4 , usando Windows Script Host resultó ser la solución más fácil para mí (probado en Windows 8 64 bit).

Sin embargo, en lugar de importar el tipo COM manualmente a través del código, es más fácil agregar la biblioteca de tipos COM como referencia. Seleccione Referencias- > Agregar referencia ... , COM- > Librerías de tipos y busque y agregue " Modelo de objetos de host de Windows Script " .

Esto importa el espacio de nombres IWshRuntimeLibrary , desde el cual puede acceder:

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

El crédito va para Jim Hollenhorst .

Donwload IWshRuntimeLibrary

También debe importar la biblioteca COM IWshRuntimeLibrary . Haz clic derecho en tu proyecto - > añadir referencia - > COM - > IWshRuntimeLibrary - > agregue 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();

}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top