如何创建桌面快捷方式

原创
2018/10/26 13:48
阅读数 174

微软用来创建快捷方式的类库,当在项目中添加Com引用"Windows Script Host Object Model "时,此类库就会出现在项目中。

1.首先要添加引用.
  添加引用的方法非常简单,右击你的项目并选择添加引用,
  选择 COM 选项卡并选择 Windows Script Host Object Model

 2.引用命名空间
  using System.Runtime.InteropServices;//互动服务
  using IWshRuntimeLibrary;

3、具体代码:

 /// <summary>
        /// 创建快捷方式
        /// </summary>
        /// <param name="lnkName"></param>
        public static void CreateShortcutOnDesktop(string lnkName)
        {
            //添加引用 (com->Windows Script Host Object Model),using IWshRuntimeLibrary;
            if (IsShortcut(lnkName) == false)
            {
                string shortcutPath = Path.Combine(Environment.GetFolderPath(
                    Environment.SpecialFolder.DesktopDirectory), lnkName + ".lnk");
                // 获取当前应用程序目录地址
                string exePath = Process.GetCurrentProcess().MainModule.FileName;
                IWshShell shell = new WshShell();
                //通过该对象的 CreateShortcut 方法来创建 IWshShortcut 接口的实例对象
                WshShortcut shortcut = (WshShortcut)shell.CreateShortcut(shortcutPath);
                shortcut.TargetPath = exePath;
                //设置应用程序的启动参数(如果应用程序支持的话)
                shortcut.Arguments = "";// 参数
                //快捷方式的描述
                shortcut.Description = "医利捷(上海)信息科技有限公司-" + lnkName;
                //当用户没有指定一个具体的目录时,快捷方式的目标应用程序将使用该属性所指定的目录来装载或保存文件。
                //程序所在文件夹,在快捷方式图标点击右键可以看到此属性
                shortcut.WorkingDirectory = Environment.CurrentDirectory;
                //可以自定义快捷方式图标.(如果不设置,则将默认源文件图标.)
                shortcut.IconLocation = exePath;//图标,该图标是应用程序的资源文件
                //目标应用程序窗口类型(1.Normal window普通窗口,3.Maximized最大化窗口,7.Minimized最小化)
                shortcut.WindowStyle = 1;
                //保存快捷方式
                shortcut.Save();
            }

        }

        /// <summary>
        /// 快捷方式 是否存在
        /// </summary>
        /// <param name="lnkName"></param>
        /// <returns></returns>
        public static bool IsShortcut(string lnkName)
        {
            string shortcutPath = Path.Combine(Environment.GetFolderPath(
                Environment.SpecialFolder.DesktopDirectory), lnkName + ".lnk");

            if (!System.IO.File.Exists(shortcutPath))
            {
                // 获取当前应用程序目录地址
                string exePath = Process.GetCurrentProcess().MainModule.FileName;
                IWshShell shell = new WshShell();
                // 确定是否已经创建的快捷键被改名了
                foreach (var item in Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "*.lnk"))
                {
                    WshShortcut tempShortcut = (WshShortcut)shell.CreateShortcut(item);
                    if (tempShortcut.TargetPath == exePath)
                    {
                        return true;
                    }
                }
            }
            return false;
        }
 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部