C#創建快捷方式

//需要引入IWshRuntimeLibrary,搜索Windows Script Host Object Model

        /// <summary>
        /// 創建快捷方式
        /// </summary>
        /// <param name="directory">快捷方式所處的文件夾</param>
        /// <param name="shortcutName">快捷方式名稱</param>
        /// <param name="targetPath">目標路徑</param>
        /// <param name="description">描述</param>
        /// <param name="iconLocation">圖標路徑,格式爲"可執行文件或DLL路徑, 圖標編號",
        /// 例如System.Environment.SystemDirectory + "\\" + "shell32.dll, 165"</param>
        /// <remarks></remarks>
        public static void CreateShortcut(string directory, string shortcutName, string targetPath,
            string description = null, string iconLocation = null)
        {
            if (!System.IO.Directory.Exists(directory))
            {
                System.IO.Directory.CreateDirectory(directory);
            }

            string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));
            WshShell shell = new WshShell();
            IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);//創建快捷方式對象
            shortcut.TargetPath = targetPath;//指定目標路徑
            shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);//設置起始位置
            shortcut.WindowStyle = 1;//設置運行方式,默認爲常規窗口
            shortcut.Description = description;//設置備註
            shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation;//設置圖標路徑
            shortcut.Save();//保存快捷方式
        }

        /// <summary>
        /// 創建桌面快捷方式
        /// </summary>
        /// <param name="shortcutName">快捷方式名稱</param>
        /// <param name="targetPath">目標路徑</param>
        /// <param name="description">描述</param>
        /// <param name="iconLocation">圖標路徑,格式爲"可執行文件或DLL路徑, 圖標編號"</param>
        /// <remarks></remarks>
        public static void CreateShortcutOnDesktop()
        {
            string targetpath = System.Windows.Forms.Application.ExecutablePath;//獲取運行程序
            string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);//獲取桌面文件夾路徑
            string Name = Path.GetFileNameWithoutExtension(targetpath);
            if (System.IO.File.Exists(desktop + "\\" + Name+ ".lnk"))
                return;
            CreateShortcut(desktop, Name, targetpath, null, null);
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章