Create a shortcut on Desktop

2019-01-02 18:00发布

I want to create a shortcut pointing to some EXE file, on the desktop, using .NET Framework 3.5 and relying on an official Windows API. How can I do that?

标签: c#
12条回答
千与千寻千般痛.
2楼-- · 2019-01-02 18:14

With additional options such as hotkey, description etc.

At first, Project > Add Reference > COM > Windows Script Host Object Model.

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.SpecialFolders.System) + @"\notepad.exe";
  shortcut.Save();
}
查看更多
谁念西风独自凉
3楼-- · 2019-01-02 18:14

I use "Windows Script Host Object Model" reference to create shortcut.

Adding "Windows Script Host Object Model" to project references

and to create shortcut on specific location:

    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();
    }
查看更多
泛滥B
4楼-- · 2019-01-02 18:17

EDIT: I do not recommend this solution anymore. If there's still no better method than using the Windows scripting engine, at least use @Mehmet's solution which calls the engine directly rather than creating a plain text script in memory.

We used VBScript to generate a shortcut. It does not need p/Invoke, COM Interop and additional DLLs. It works like this:

  • Generate a VBScript at runtime with the specified parameters of the CreateShortcut C# method
  • Save this VBScript in a temporary file
  • Wait for the script to finish
  • Delete the temporary file

Here you go:

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);
}
查看更多
闭嘴吧你
5楼-- · 2019-01-02 18:24

Here's a (Tested) Extension Method, with comments to help you out.

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

And an example of use:

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

1st parm sets the exe name (found in the current directory) 2nd parm is the "Start In" folder and 3rd parm is the shortcut description.

Example of Using this code

The naming convention of the link leaves no ambiguity as to what it will do. To test the link just double click it.

Final Note: the application itself (target) must have an ICON image associated with it. The link is easily able to locate the ICON within the exe. If the target application has more than one icon, you may open the link's properties and change the icon to any other found in the exe.

查看更多
若你有天会懂
6楼-- · 2019-01-02 18:26
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");
    }
查看更多
忆尘夕之涩
7楼-- · 2019-01-02 18:27

You can use this ShellLink.cs class to create the shortcut.

To get the desktop directory, use:

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

or use Environment.SpecialFolder.CommonDesktopDirectory to create it for all users.

查看更多
登录 后发表回答