Erstellen Sie eine Verknüpfung auf dem Desktop


106

Ich möchte mit .NET Framework 3.5 und unter Verwendung einer offiziellen Windows-API eine Verknüpfung erstellen, die auf eine EXE-Datei auf dem Desktop verweist. Wie kann ich das machen?


1
Die Verwendung des Windows Script Host-Objektmodells von Rustam Irzaev ist das einzig zuverlässige Modell für eine ordnungsgemäße Verknüpfung. ayush: Bei dieser Technik fehlen eine Reihe von Funktionen wie Tastenkombinationen und Beschreibungen. Thorarin: ShellLink funktioniert in den meisten Fällen gut, aber insbesondere nicht unter Windows XP und erstellt ungültige Verknüpfungen. Simon Mourier: Das war sehr vielversprechend, erstellt aber ungültige Verknüpfungen in Windows 8.
BrutalDev

Die Antwort von Simon Mourier ist hier die beste Antwort. Die einzige korrekte und kugelsichere Methode zum Erstellen von Verknüpfungen ist die Verwendung derselben API, die das Betriebssystem verwendet, und dies ist die IShellLink-Schnittstelle. Verwenden Sie keinen Windows Script Host und erstellen Sie keine Weblinks! Simon Mourier zeigt, wie das mit 6 Codezeilen geht. Jeder, der Probleme mit dieser Methode hatte, hat SICHER ungültige Pfade übergeben. Ich habe seinen Code unter Windows XP, 7 und 10 getestet. Kompilieren Sie Ihre App als "Beliebige CPU", um Probleme mit 32/64-Bit-Windows zu vermeiden, die unterschiedliche Ordner für Programme verwenden.
Elmue

Antworten:


120

Mit zusätzlichen Optionen wie Hotkey, Beschreibung usw.

Wählen Sie zunächst Projekt > Referenz hinzufügen > COM > Windows Script Host-Objektmodell.

using IWshRuntimeLibrary;

private void CreateShortcut()
{
  object shDesktop = (object)"Desktop";
  WshShell shell = new WshShell();
  string shortcutAddress = (string)shell.SpecialFolders.Item(ref shDesktop) + @"\Notepad.lnk";
  IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutAddress);
  shortcut.Description = "New shortcut for a Notepad";
  shortcut.Hotkey = "Ctrl+Shift+N";
  shortcut.TargetPath = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\notepad.exe";
  shortcut.Save();
}

2
Das war sehr nah für mich. Ich musste das Verzeichnis .exe zur Eigenschaft "WorkingDirectory" auf der Verknüpfung hinzufügen. (Abkürzung.Arbeitsverzeichnis) +1
samuelesque

4
Verwenden Sie zum Angeben eines Symbolindex (in IconLocation) einen Wert wie "path_to_icon_file, #", wobei # der Symbolindex ist. Siehe msdn.microsoft.com/en-us/library/xsy6k3ys(v=vs.84).aspx
Chris

1
für Argument: shortcut.Arguments = "Seta Map mp_crash"; stackoverflow.com/a/18491229/2155778
Zolfaghari

7
Environment.SpecialFolders.System - existiert nicht ... Environment.SpecialFolder.System - funktioniert.
JSWulf

Für das Muss der Zeit müssen Sie auch Microsoft.CSharp als Referenz hinzufügen.
l1nuxuser

76

URL-Verknüpfung

private void urlShortcutToDesktop(string linkName, string linkUrl)
{
    string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

    using (StreamWriter writer = new StreamWriter(deskDir + "\\" + linkName + ".url"))
    {
        writer.WriteLine("[InternetShortcut]");
        writer.WriteLine("URL=" + linkUrl);
    }
}

Anwendungsverknüpfung

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

Überprüfen Sie auch dieses Beispiel .

Wenn Sie einige API-spezifische Funktionen verwenden möchten, sollten Sie sowohl die IShellLink interfaceals auch die IPersistFile interface(über COM-Interop) verwenden.

In diesem Artikel wird detailliert beschrieben, was Sie dazu benötigen, sowie Beispielcode.


Diese oben funktionieren gut. Aber ich möchte eine Verknüpfung über einige API-Funktionen wie DllImport ("coredll.dll")] public static extern int SHCreateShortcut (StringBuilder szShortcut, StringBuilder szTarget) erstellen;
Vipin Arora

@ VIPin warum? Gibt es einen Grund, warum eine der oben genannten Lösungen nicht gut genug ist?
alex

8
Nitpicking: Sie könnten die Flush () - Zeile entfernen, da die Beendigung des Using-Blocks dies für Sie erledigen sollte
Newtopian

3
Ich hatte viele Probleme mit dieser Methode ... Windows neigt dazu, die Verknüpfungsdefinition irgendwo zwischenzuspeichern ... eine Verknüpfung wie diese zu erstellen, sie zu löschen und dann eine mit demselben Namen, aber einer anderen URL zu erstellen ... wahrscheinlich sind Windows öffnet die alte gelöschte URL, wenn Sie auf die Verknüpfung klicken. Rustams Antwort unten (mit .lnk anstelle von .url) löste dieses Problem für mich
TCC

1
Tolle Antwort. Viel besser als die schrecklichen COM-Installationen, mit denen Sie bei der Verwendung von .lnk-Dateien umgehen müssen.
James Ko

61

Hier ist ein Code, der keine Abhängigkeit von einem externen COM-Objekt (WSH) hat und 32-Bit- und 64-Bit-Programme unterstützt:

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;

namespace TestShortcut
{
    class Program
    {
        static void Main(string[] args)
        {
            IShellLink link = (IShellLink)new ShellLink();

            // setup shortcut information
            link.SetDescription("My Description");
            link.SetPath(@"c:\MyPath\MyProgram.exe");

            // save it
            IPersistFile file = (IPersistFile)link;
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            file.Save(Path.Combine(desktopPath, "MyLink.lnk"), false);
        }
    }

    [ComImport]
    [Guid("00021401-0000-0000-C000-000000000046")]
    internal class ShellLink
    {
    }

    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("000214F9-0000-0000-C000-000000000046")]
    internal interface IShellLink
    {
        void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out IntPtr pfd, int fFlags);
        void GetIDList(out IntPtr ppidl);
        void SetIDList(IntPtr pidl);
        void GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName);
        void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
        void GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath);
        void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);
        void GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath);
        void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);
        void GetHotkey(out short pwHotkey);
        void SetHotkey(short wHotkey);
        void GetShowCmd(out int piShowCmd);
        void SetShowCmd(int iShowCmd);
        void GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath, int cchIconPath, out int piIcon);
        void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
        void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved);
        void Resolve(IntPtr hwnd, int fFlags);
        void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);
    }
}

@BrutalDev - Was funktioniert nicht? Ich habe es unter Windows 8 x64 getestet und es funktioniert.
Simon Mourier

Wenn Sie auch Win8 x64 ausführen und das obige Codebeispiel genau so kopieren, wie es ist, wird auf meinem Desktop ein Symbol ohne Pfad erstellt. Durch Ausführen des Links wird nur der Explorer für den Desktop geöffnet. Dies ist ein ähnliches Problem, das ich mit ShellLink.cs hatte, aber unter Windows XP / 2003. Das einzige Beispiel, das definitiv für alle Windows-Versionen funktioniert, war die Verwendung von WSHOM durch Rustam Irzaev, wie ich in meinem Kommentar zur Hauptfrage erwähnt habe: "Dies war sehr vielversprechend, erstellt jedoch ungültige Verknüpfungen in Windows 8"
BrutalDev,

Ich habe dies unter Windows 8.1 x64 zum Laufen gebracht, aber der hier angegebene Code hat keine Definition für IPersistFile. Ich musste das aus dem ShellLink.cs- Beitrag kopieren , damit es funktioniert.
Walter Wilfinger

Ich sehe keinen konkreten Grund, warum dies nicht funktionieren würde. Wie auch immer, IPersistFile ist sofort in System.Runtime.InteropServices.ComTypes verfügbar
Simon Mourier

1
Diese Lösung setzt unter SetIconLocation64-Bit-Windows 10 mit ausführbarer 32-Bit-Datei kein korrektes Symbol . Die Lösung wird hier beschrieben: stackoverflow.com/a/39282861 und ich vermute auch, dass es sich um das gleiche Problem mit Windows 8 handelt, auf das sich alle anderen beziehen. Dies kann mit 32-Bit-Exe-Dateien unter 64-Bit-Windows zusammenhängen.
Maris B.

26

Mit dieser ShellLink.cs- Klasse können Sie die Verknüpfung erstellen.

Verwenden Sie zum Abrufen des Desktop-Verzeichnisses:

var dir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

oder verwenden Sie Environment.SpecialFolder.CommonDesktopDirectory, um es für alle Benutzer zu erstellen.


6
@Vipin: Wenn eine Lösung für Sie funktioniert, ist es üblich, sie zu verbessern. Außerdem sollten Sie die beste Lösung auswählen und als Antwort auf Ihr Problem akzeptieren.
Thorarin

Dadurch wird die vorhandene exe mit der lnk-Datei überschrieben. Getestet auf Win10.
Zwcloud

@zwcloud Dieser Code überschreibt nichts, weil er nichts tut. Es sagt Ihnen nur, welche Klassen und Methoden Sie verwenden müssen, um mit Verknüpfungen zu arbeiten. Wenn Ihr Code die Exe überschreibt, die auf Ihnen liegt. Ich würde mir ansehen, wie Sie die lnk-Datei tatsächlich erstellen, um zu sehen, warum sie Ihre Exe zerstört.
Cdaragorn

15

Ohne zusätzlichen Hinweis:

using System;
using System.Runtime.InteropServices;

public class Shortcut
{

private static Type m_type = Type.GetTypeFromProgID("WScript.Shell");
private static object m_shell = Activator.CreateInstance(m_type);

[ComImport, TypeLibType((short)0x1040), Guid("F935DC23-1CF0-11D0-ADB9-00C04FD58A0B")]
private interface IWshShortcut
{
    [DispId(0)]
    string FullName { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0)] get; }
    [DispId(0x3e8)]
    string Arguments { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3e8)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3e8)] set; }
    [DispId(0x3e9)]
    string Description { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3e9)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3e9)] set; }
    [DispId(0x3ea)]
    string Hotkey { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3ea)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3ea)] set; }
    [DispId(0x3eb)]
    string IconLocation { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3eb)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3eb)] set; }
    [DispId(0x3ec)]
    string RelativePath { [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3ec)] set; }
    [DispId(0x3ed)]
    string TargetPath { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3ed)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3ed)] set; }
    [DispId(0x3ee)]
    int WindowStyle { [DispId(0x3ee)] get; [param: In] [DispId(0x3ee)] set; }
    [DispId(0x3ef)]
    string WorkingDirectory { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3ef)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3ef)] set; }
    [TypeLibFunc((short)0x40), DispId(0x7d0)]
    void Load([In, MarshalAs(UnmanagedType.BStr)] string PathLink);
    [DispId(0x7d1)]
    void Save();
}

public static void Create(string fileName, string targetPath, string arguments, string workingDirectory, string description, string hotkey, string iconPath)
{
    IWshShortcut shortcut = (IWshShortcut)m_type.InvokeMember("CreateShortcut", System.Reflection.BindingFlags.InvokeMethod, null, m_shell, new object[] { fileName });
    shortcut.Description = description;
    shortcut.Hotkey = hotkey;
    shortcut.TargetPath = targetPath;
    shortcut.WorkingDirectory = workingDirectory;
    shortcut.Arguments = arguments;
    if (!string.IsNullOrEmpty(iconPath))
        shortcut.IconLocation = iconPath;
    shortcut.Save();
}
}

So erstellen Sie eine Verknüpfung auf dem Desktop:

    string lnkFileName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Notepad.lnk");
    Shortcut.Create(lnkFileName,
        System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "notepad.exe"),
        null, null, "Open Notepad", "Ctrl+Shift+N", null);

11

Ich benutze einfach für meine App:

using IWshRuntimeLibrary; // > Ref > COM > Windows Script Host Object  
...   
private static void CreateShortcut()
    {
        string link = Environment.GetFolderPath( Environment.SpecialFolder.Desktop ) 
            + Path.DirectorySeparatorChar + Application.ProductName + ".lnk";
        var shell = new WshShell();
        var shortcut = shell.CreateShortcut( link ) as IWshShortcut;
        shortcut.TargetPath = Application.ExecutablePath;
        shortcut.WorkingDirectory = Application.StartupPath;
        //shortcut...
        shortcut.Save();
    }

Funktioniert
sofort

9

Verwenden Sie ShellLink.cs bei vbAccelerator, um Ihre Verknüpfung einfach zu erstellen!

private static void AddShortCut()
{
using (ShellLink shortcut = new ShellLink())
{
    shortcut.Target = Application.ExecutablePath;
    shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath);
    shortcut.Description = "My Shorcut";
    shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;
    shortcut.Save(SHORTCUT_FILEPATH);
}
}

3
Dieser Link ist jetzt tot, aber eine archivierte Version davon finden Sie hier .
pswg

7

Hier ist mein Code:

public static class ShortcutHelper
{
    #region Constants
    /// <summary>
    /// Default shortcut extension
    /// </summary>
    public const string DEFAULT_SHORTCUT_EXTENSION = ".lnk";

    private const string WSCRIPT_SHELL_NAME = "WScript.Shell";
    #endregion

    /// <summary>
    /// Create shortcut in current path.
    /// </summary>
    /// <param name="linkFileName">shortcut name(include .lnk extension.)</param>
    /// <param name="targetPath">target path</param>
    /// <param name="workingDirectory">working path</param>
    /// <param name="arguments">arguments</param>
    /// <param name="hotkey">hot key(ex: Ctrl+Shift+Alt+A)</param>
    /// <param name="shortcutWindowStyle">window style</param>
    /// <param name="description">shortcut description</param>
    /// <param name="iconNumber">icon index(start of 0)</param>
    /// <returns>shortcut file path.</returns>
    /// <exception cref="System.IO.FileNotFoundException"></exception>
    public static string CreateShortcut(
        string linkFileName,
        string targetPath,
        string workingDirectory = "",
        string arguments = "",
        string hotkey = "",
        ShortcutWindowStyles shortcutWindowStyle = ShortcutWindowStyles.WshNormalFocus,
        string description = "",
        int iconNumber = 0)
    {
        if (linkFileName.Contains(DEFAULT_SHORTCUT_EXTENSION) == false)
        {
            linkFileName = string.Format("{0}{1}", linkFileName, DEFAULT_SHORTCUT_EXTENSION);
        }

        if (File.Exists(targetPath) == false)
        {
            throw new FileNotFoundException(targetPath);
        }

        if (workingDirectory == string.Empty)
        {
            workingDirectory = Path.GetDirectoryName(targetPath);
        }

        string iconLocation = string.Format("{0},{1}", targetPath, iconNumber);

        if (Environment.Version.Major >= 4)
        {
            Type shellType = Type.GetTypeFromProgID(WSCRIPT_SHELL_NAME);
            dynamic shell = Activator.CreateInstance(shellType);
            dynamic shortcut = shell.CreateShortcut(linkFileName);

            shortcut.TargetPath = targetPath;
            shortcut.WorkingDirectory = workingDirectory;
            shortcut.Arguments = arguments;
            shortcut.Hotkey = hotkey;
            shortcut.WindowStyle = shortcutWindowStyle;
            shortcut.Description = description;
            shortcut.IconLocation = iconLocation;

            shortcut.Save();
        }
        else
        {
            Type shellType = Type.GetTypeFromProgID(WSCRIPT_SHELL_NAME);
            object shell = Activator.CreateInstance(shellType);
            object shortcut = shellType.InvokeMethod("CreateShortcut", shell, linkFileName);
            Type shortcutType = shortcut.GetType();

            shortcutType.InvokeSetMember("TargetPath", shortcut, targetPath);
            shortcutType.InvokeSetMember("WorkingDirectory", shortcut, workingDirectory);
            shortcutType.InvokeSetMember("Arguments", shortcut, arguments);
            shortcutType.InvokeSetMember("Hotkey", shortcut, hotkey);
            shortcutType.InvokeSetMember("WindowStyle", shortcut, shortcutWindowStyle);
            shortcutType.InvokeSetMember("Description", shortcut, description);
            shortcutType.InvokeSetMember("IconLocation", shortcut, iconLocation);

            shortcutType.InvokeMethod("Save", shortcut);
        }

        return Path.Combine(System.Windows.Forms.Application.StartupPath, linkFileName);
    }

    private static object InvokeSetMember(this Type type, string methodName, object targetInstance, params object[] arguments)
    {
        return type.InvokeMember(
            methodName,
            BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty,
            null,
            targetInstance,
            arguments);
    }

    private static object InvokeMethod(this Type type, string methodName, object targetInstance, params object[] arguments)
    {
        return type.InvokeMember(
            methodName,
            BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod,
            null,
            targetInstance,
            arguments);
    }

    /// <summary>
    /// windows styles
    /// </summary>
    public enum ShortcutWindowStyles
    {
        /// <summary>
        /// Hide
        /// </summary>
        WshHide = 0,
        /// <summary>
        /// NormalFocus
        /// </summary>
        WshNormalFocus = 1,
        /// <summary>
        /// MinimizedFocus
        /// </summary>
        WshMinimizedFocus = 2,
        /// <summary>
        /// MaximizedFocus
        /// </summary>
        WshMaximizedFocus = 3,
        /// <summary>
        /// NormalNoFocus
        /// </summary>
        WshNormalNoFocus = 4,
        /// <summary>
        /// MinimizedNoFocus
        /// </summary>
        WshMinimizedNoFocus = 6,
    }
}

5

EDIT: Ich empfehle diese Lösung nicht mehr. Wenn es immer noch keine bessere Methode als die Verwendung der Windows-Skript-Engine gibt, verwenden Sie zumindest die Lösung von @ Mehmet, die die Engine direkt aufruft, anstatt ein Nur-Text-Skript im Speicher zu erstellen.

Wir haben VBScript verwendet, um eine Verknüpfung zu generieren. Es werden keine p / Invoke-, COM-Interop- und zusätzlichen DLLs benötigt. Es funktioniert so:

  • Generieren Sie zur Laufzeit ein VBScript mit den angegebenen Parametern der CreateShortcut C # -Methode
  • Speichern Sie dieses VBScript in einer temporären Datei
  • Warten Sie, bis das Skript beendet ist
  • Löschen Sie die temporäre Datei

Bitte schön:

static string _scriptTempFilename;

/// <summary>
/// Creates a shortcut at the specified path with the given target and
/// arguments.
/// </summary>
/// <param name="path">The path where the shortcut will be created. This should
///     be a file with the LNK extension.</param>
/// <param name="target">The target of the shortcut, e.g. the program or file
///     or folder which will be opened.</param>
/// <param name="arguments">The additional command line arguments passed to the
///     target.</param>
public static void CreateShortcut(string path, string target, string arguments)
{
    // Check if link path ends with LNK or URL
    string extension = Path.GetExtension(path).ToUpper();
    if (extension != ".LNK" && extension != ".URL")
    {
        throw new ArgumentException("The path of the shortcut must have the extension .lnk or .url.");
    }

    // Get temporary file name with correct extension
    _scriptTempFilename = Path.GetTempFileName();
    File.Move(_scriptTempFilename, _scriptTempFilename += ".vbs");

    // Generate script and write it in the temporary file
    File.WriteAllText(_scriptTempFilename, String.Format(@"Dim WSHShell
Set WSHShell = WScript.CreateObject({0}WScript.Shell{0})
Dim Shortcut
Set Shortcut = WSHShell.CreateShortcut({0}{1}{0})
Shortcut.TargetPath = {0}{2}{0}
Shortcut.WorkingDirectory = {0}{3}{0}
Shortcut.Arguments = {0}{4}{0}
Shortcut.Save",
        "\"", path, target, Path.GetDirectoryName(target), arguments),
        Encoding.Unicode);

    // Run the script and delete it after it has finished
    Process process = new Process();
    process.StartInfo.FileName = _scriptTempFilename;
    process.Start();
    process.WaitForExit();
    File.Delete(_scriptTempFilename);
}

3

Hier ist eine (getestete) Erweiterungsmethode mit Kommentaren, die Ihnen helfen sollen.

using IWshRuntimeLibrary;
using System;

namespace Extensions
{
    public static class XShortCut
    {
        /// <summary>
        /// Creates a shortcut in the startup folder from a exe as found in the current directory.
        /// </summary>
        /// <param name="exeName">The exe name e.g. test.exe as found in the current directory</param>
        /// <param name="startIn">The shortcut's "Start In" folder</param>
        /// <param name="description">The shortcut's description</param>
        /// <returns>The folder path where created</returns>
        public static string CreateShortCutInStartUpFolder(string exeName, string startIn, string description)
        {
            var startupFolderPath = Environment.SpecialFolder.Startup.GetFolderPath();
            var linkPath = startupFolderPath + @"\" + exeName + "-Shortcut.lnk";
            var targetPath = Environment.CurrentDirectory + @"\" + exeName;
            XFile.Delete(linkPath);
            Create(linkPath, targetPath, startIn, description);
            return startupFolderPath;
        }

        /// <summary>
        /// Create a shortcut
        /// </summary>
        /// <param name="fullPathToLink">the full path to the shortcut to be created</param>
        /// <param name="fullPathToTargetExe">the full path to the exe to 'really execute'</param>
        /// <param name="startIn">Start in this folder</param>
        /// <param name="description">Description for the link</param>
        public static void Create(string fullPathToLink, string fullPathToTargetExe, string startIn, string description)
        {
            var shell = new WshShell();
            var link = (IWshShortcut)shell.CreateShortcut(fullPathToLink);
            link.IconLocation = fullPathToTargetExe;
            link.TargetPath = fullPathToTargetExe;
            link.Description = description;
            link.WorkingDirectory = startIn;
            link.Save();
        }
    }
}

Und ein Anwendungsbeispiel:

XShortCut.CreateShortCutInStartUpFolder(THEEXENAME, 
    Environment.CurrentDirectory,
    "Starts some executable in the current directory of application");

Der erste Parameter legt den Exe-Namen fest (im aktuellen Verzeichnis). Der zweite Parameter ist der Ordner "Start In" und der dritte Parameter ist die Beschreibung der Verknüpfung.

Beispiel für die Verwendung dieses Codes

Die Namenskonvention des Links lässt keine Unklarheit darüber, was er tun wird. Um den Link zu testen, doppelklicken Sie einfach darauf.

Schlussbemerkung: Der Anwendung selbst (Ziel) muss ein ICON-Image zugeordnet sein. Der Link kann das ICON innerhalb der Exe leicht lokalisieren. Wenn die Zielanwendung mehr als ein Symbol enthält, können Sie die Eigenschaften des Links öffnen und das Symbol in ein anderes Symbol in der Exe ändern.


Ich erhalte die Fehlermeldung, dass .GetFolderPath () nicht vorhanden ist. Gleiches gilt für XFile.Delete. Was vermisse ich?
RalphF

Tritt hier ein Fehler auf? Environment.SpecialFolder.Startup.GetFolderPath ();
John Peters

2

Ich verwende die Referenz "Windows Script Host Object Model", um eine Verknüpfung zu erstellen.

Hinzufügen von "Windows Script Host Object Model" zu Projektreferenzen

und um eine Verknüpfung an einem bestimmten Ort zu erstellen:

    void CreateShortcut(string linkPath, string filename)
    {
        // Create shortcut dir if not exists
        if (!Directory.Exists(linkPath))
            Directory.CreateDirectory(linkPath);

        // shortcut file name
        string linkName = Path.ChangeExtension(Path.GetFileName(filename), ".lnk");

        // COM object instance/props
        IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
        IWshRuntimeLibrary.IWshShortcut sc = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(linkName);
        sc.Description = "some desc";
        //shortcut.IconLocation = @"C:\..."; 
        sc.TargetPath = linkPath;
        // save shortcut to target
        sc.Save();
    }

0
private void CreateShortcut(string executablePath, string name)
    {
        CMDexec("echo Set oWS = WScript.CreateObject('WScript.Shell') > CreateShortcut.vbs");
        CMDexec("echo sLinkFile = '" + Environment.GetEnvironmentVariable("homedrive") + "\\users\\" + Environment.GetEnvironmentVariable("username") + "\\desktop\\" + name + ".ink' >> CreateShortcut.vbs");
        CMDexec("echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs");
        CMDexec("echo oLink.TargetPath = '" + executablePath + "' >> CreateShortcut.vbs");
        CMDexec("echo oLink.Save >> CreateShortcut.vbs");
        CMDexec("cscript CreateShortcut.vbs");
        CMDexec("del CreateShortcut.vbs");
    }

0

Ich habe eine Wrapper-Klasse basierend auf Rustam Irzaevs Antwort unter Verwendung von IWshRuntimeLibrary erstellt.

IWshRuntimeLibrary -> Referenzen -> COM> Windows Script Host-Objektmodell

using System;
using System.IO;
using IWshRuntimeLibrary;
using File = System.IO.File;

public static class Shortcut
{
    public static void CreateShortcut(string originalFilePathAndName, string destinationSavePath)
    {
        string fileName = Path.GetFileNameWithoutExtension(originalFilePathAndName);
        string originalFilePath = Path.GetDirectoryName(originalFilePathAndName);

        string link = destinationSavePath + Path.DirectorySeparatorChar + fileName + ".lnk";
        var shell = new WshShell();
        var shortcut = shell.CreateShortcut(link) as IWshShortcut;
        if (shortcut != null)
        {
            shortcut.TargetPath = originalFilePathAndName;
            shortcut.WorkingDirectory = originalFilePath;
            shortcut.Save();
        }
    }

    public static void CreateStartupShortcut()
    {
        CreateShortcut(System.Reflection.Assembly.GetEntryAssembly()?.Location, Environment.GetFolderPath(Environment.SpecialFolder.Startup));
    }

    public static void DeleteShortcut(string originalFilePathAndName, string destinationSavePath)
    {
        string fileName = Path.GetFileNameWithoutExtension(originalFilePathAndName);
        string originalFilePath = Path.GetDirectoryName(originalFilePathAndName);

        string link = destinationSavePath + Path.DirectorySeparatorChar + fileName + ".lnk";
        if (File.Exists(link)) File.Delete(link);
    }

    public static void DeleteStartupShortcut()
    {
        DeleteShortcut(System.Reflection.Assembly.GetEntryAssembly()?.Location, Environment.GetFolderPath(Environment.SpecialFolder.Startup));
    }
}

-2

Für Windows Vista / 7/8/10 können Sie stattdessen einen Symlink über erstellen mklink.

Process.Start("cmd.exe", $"/c mklink {linkName} {applicationPath}");

Alternativ können Sie auch CreateSymbolicLinküber P / Invoke anrufen .


Dies hat nichts mit einer Verknüpfung zu tun.
Matt
Durch die Nutzung unserer Website bestätigen Sie, dass Sie unsere Cookie-Richtlinie und Datenschutzrichtlinie gelesen und verstanden haben.
Licensed under cc by-sa 3.0 with attribution required.