C# 在桌面上创建快捷方式

C# 在桌面上创建快捷方式,c#,C#,我想创建一个指向桌面上某个EXE文件的快捷方式,使用.NET Framework 3.5并依赖于官方的Windows API。我该怎么做 URL快捷方式 private void urlShortcutToDesktop(string linkName, string linkUrl) { string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); using (

我想创建一个指向桌面上某个EXE文件的快捷方式,使用.NET Framework 3.5并依赖于官方的Windows API。我该怎么做

URL快捷方式

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);
    }
}
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);
    }
}
应用程序快捷方式

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);
    }
}
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);
    }
}
也检查一下这个

如果要使用某些特定于API的函数,则需要使用
IShellLink接口
以及
IPersistFile接口
(通过COM互操作)

您可以使用此类创建快捷方式

要获取桌面目录,请使用:

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

或者使用
Environment.SpecialFolder.CommonDesktopDirectory
为所有用户创建它。

带有热键、说明等附加选项

首先,Project添加引用COMWindows脚本主机对象模型

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();
}
使用vbAccelerator轻松创建快捷方式

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

无需额外参考:

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();
}
}
要在桌面上创建快捷方式,请执行以下操作:

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

下面是一段代码,它不依赖于外部COM对象(WSH),并且支持32位和64位程序:

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);
    }
}
我使用“Windows脚本主机对象模型”引用创建快捷方式

要在特定位置创建快捷方式,请执行以下操作:

    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();
    }
这是我的密码:

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,
    }
}
公共静态类ShortcutHelper
{
#区域常数
/// 
///默认快捷方式扩展名
/// 
public const string DEFAULT_SHORTCUT_EXTENSION=“.lnk”;
私有常量字符串WSCRIPT\u SHELL\u NAME=“WSCRIPT.SHELL”;
#端区
/// 
///在当前路径中创建快捷方式。
/// 
///快捷方式名称(包括.lnk扩展名。)
///目标路径
///工作路径
///论据
///热键(例如:Ctrl+Shift+Alt+A)
///窗口样式
///快捷方式描述
///图标索引(从0开始)
///快捷方式文件路径。
/// 
公共静态字符串快捷方式(
字符串链接文件名,
字符串targetPath,
字符串workingDirectory=“”,
字符串参数=”,
字符串热键=”,
ShortcutWindowStyles shortcutWindowStyle=ShortcutWindowStyles.WshNormalFocus,
字符串说明=”,
int iconNumber=0)
{
if(linkFileName.Contains(默认快捷方式扩展名)=false)
{
linkFileName=string.Format(“{0}{1}”,linkFileName,默认的快捷方式扩展名);
}
if(File.Exists(targetPath)==false)
{
抛出新的FileNotFoundException(targetPath);
}
if(workingDirectory==string.Empty)
{
workingDirectory=Path.GetDirectoryName(targetPath);
}
字符串iconLocation=string.Format(“{0},{1}”,targetPath,iconNumber);
如果(Environment.Version.Major>=4)
{
Type shellType=Type.GetTypeFromProgID(WSCRIPT\u SHELL\u名称);
dynamic shell=Activator.CreateInstance(shellType);
动态快捷方式=shell.CreateShortcut(linkFileName);
shortcut.TargetPath=TargetPath;
shortcut.WorkingDirectory=工作目录;
参数=参数;
快捷键。热键=热键;
shortcut.WindowStyle=shortcutWindowStyle;
快捷方式。描述=描述;
shortcut.IconLocation=IconLocation;
shortcut.Save();
}
其他的
{
Type shellType=Type.GetTypeFromProgID(WSCRIPT\u SHELL\u名称);
object shell=Activator.CreateInstance(shellType);
对象快捷方式=shellType.InvokeMethod(“CreateShortcut”,shell,linkFileName);
Type shortcutType=shortcut.GetType();
InvokeSetMember(“TargetPath”,快捷方式,TargetPath);
InvokeSetMember(“工作目录”,快捷方式,工作目录);
InvokeSetMember(“参数”,快捷方式,参数);
InvokeSetMember(“热键”,快捷键,热键);
InvokeSetMember(“WindowStyle”,快捷方式,shortcutWindowStyle);
InvokeSetMember(“说明”,快捷方式,说明);
InvokeSetMember(“IconLocation”,快捷方式,IconLocation);
调用方法(“保存”,快捷方式);
}
返回路径.Combine(System.Windows.Forms.Application.StartupPath,linkFileName);
}
私有静态对象InvokeSetMember(此类型、字符串方法名、对象targetInstance、params对象[]参数)
{
返回类型.InvokeMember(
方法名,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty,
无效的
目标立场,
论据);
}
私有静态对象InvokeMethod(此类型、字符串方法名、对象targetInstance、参数对象[]参数)
{
返回类型.InvokeMember(
方法名,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod,
无效的
目标立场,
论据);
}
/// 
///窗口样式
/// 
公共枚举ShortcutWindowsStyles
{
/// 
///隐藏
/// 
WshHide=0,
/// 
///正常聚焦
/// 
WshNormalFocus=1,
/// 
///最小化焦点
/// 
WshMinimizedFocus=2,
/// 
///最大化焦点
/// 
WshMaximizedFocus=3,
/// 
///正常聚焦
/// 
WshNormalNoFocus=4,
/// 
///最小化无焦点
/// 
WshMinimizedNoFocus=6,
}
}

我只为我的应用程序使用:

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();
    }
这里有一个(经过测试的)扩展方法,有一些注释可以帮助您

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();
        }
    }
}
第一个parm设置exe名称(在当前目录中找到)。第二个parm是“起始位置”文件夹,第三个parm是快捷方式描述

命名约定
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));
    }
}
using IWshRuntimeLibrary;

WshShell shell = new WshShell();
IWshShortcut shortcut = shell.CreateShortcut(@"C:\FOLDER\SOFTWARENAME.lnk");
shortcut.TargetPath = @"C:\FOLDER\SOFTWARE.exe";
shortcut.Save();