Shortcut.cs 2.9 KB
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using IWshRuntimeLibrary;
using Microsoft.Win32;

namespace BLL
{
    /// <summary>
    /// 快捷方式
    /// </summary>
    public static class Shortcut
    {
        /// <summary>
        ///  创建文件的快捷方式
        /// </summary>
        /// <returns>成功或失败</returns>
        public static bool Create()
        {
            try
            {
                string appPath = Process.GetCurrentProcess().MainModule.FileName;
                string lnkPath = GetStartupPath();
                WshShell shell = new WshShell();

                IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(lnkPath);   //创建快捷方式对象
                shortcut.TargetPath = appPath;                                         //指定目标路径
                shortcut.WorkingDirectory = Path.GetDirectoryName(appPath);            //设置起始位置
                shortcut.WindowStyle = 1;                                              //设置运行方式,默认为常规窗口
                shortcut.Description = "";                                             //设置备注
                shortcut.IconLocation = appPath;                                       //设置图标路径
                shortcut.Save();                                                       //保存快捷方式
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 删除程序的快捷方式
        /// </summary>
        public static void Delete()
        {
            string lnkPath = GetStartupPath();
            if (System.IO.File.Exists(lnkPath))
                System.IO.File.Delete(lnkPath);
        }

        /// <summary>
        /// 快捷方式是否存在
        /// </summary>
        /// <returns></returns>
        public static bool Exists()
        {
            string directory = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            string lnkPath = GetStartupPath();

            string[] files = Directory.GetFiles(directory, "*.lnk");
            int index = Array.FindIndex(files, arr => arr == lnkPath);
            if (index == -1) return false;
            else return true;

        }



        /// <summary>
        /// 获取启动文件夹内的快捷方式的lnk文件路径
        /// </summary>
        /// <returns></returns>
        private static string GetStartupPath()
        {
            string appPath = Process.GetCurrentProcess().MainModule.FileName;
            string appName = Path.GetFileNameWithoutExtension(appPath);
            string directory = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            string lnkPath = Path.Combine(directory, string.Format("{0}.lnk", appName));
            return lnkPath;
        }
    }
}