| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394 | //using IWshRuntimeLibrary;using Microsoft.Win32;using System;using System.Collections.Generic;using System.Diagnostics;using System.IO;using System.Linq;using System.Reflection;using System.Security.Principal;using System.Text;using System.Threading.Tasks;namespace Ips.Library.Basic{    /// <summary>    /// windows环境下专用,先不编译    /// </summary>    public class ToolAutoRun    {        #region 快捷方式自启        /// <summary>        /// 自动获取系统自动启动目录        /// </summary>        private static string systemStartPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.Startup); } }        /// <summary>        /// 自动获取程序完整路径        /// </summary>        private static string appAllPath { get { return Process.GetCurrentProcess().MainModule.FileName; } }        /// <summary>        /// 自动获取桌面目录        /// </summary>        private static string desktopPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); } }        /// <summary>        /// 设置开机自动启动-只需要调用改方法就可以了参数里面的bool变量是控制开机启动的开关的,默认为开启自启启动        /// </summary>        /// <param name="onOff">自启开关</param>        public static void SetAutoStartByQuick(bool onOff = true)        {            if (onOff)//开机启动            {                //获取启动路径应用程序快捷方式的路径集合                List<string> shortcutPaths = GetQuickFromFolder(systemStartPath, appAllPath);                //存在2个以快捷方式则保留一个快捷方式-避免重复多于                if (shortcutPaths.Count >= 2)                {                    for (int i = 1; i < shortcutPaths.Count; i++)                    {                        DeleteFile(shortcutPaths[i]);                    }                }                else if (shortcutPaths.Count < 1)//不存在则创建快捷方式                {                    CreateShortcut(systemStartPath, Path.GetFileNameWithoutExtension(appAllPath), appAllPath, "");                }            }            else//开机不启动            {                //获取启动路径应用程序快捷方式的路径集合                List<string> shortcutPaths = GetQuickFromFolder(systemStartPath, appAllPath);                //存在快捷方式则遍历全部删除                if (shortcutPaths.Count > 0)                {                    for (int i = 0; i < shortcutPaths.Count; i++)                    {                        DeleteFile(shortcutPaths[i]);                    }                }            }            //创建桌面快捷方式-如果需要可以取消注释            //CreateDesktopQuick(desktopPath, QuickName, appAllPath);        }        /// <summary>        /// 获取指定文件夹下指定应用程序的快捷方式路径集合        /// </summary>        /// <param name="directory">文件夹</param>        /// <param name="targetPath">目标应用程序路径</param>        /// <returns>目标应用程序的快捷方式</returns>        private static List<string> GetQuickFromFolder(string directory, string targetPath)        {            List<string> tempStrs = new List<string>();            tempStrs.Clear();            string tempStr = null;            string[] files = Directory.GetFiles(directory, "*.lnk");            if (files == null || files.Length < 1)            {                return tempStrs;            }            for (int i = 0; i < files.Length; i++)            {                //files[i] = string.Format("{0}\\{1}", directory, files[i]);                tempStr = GetAppPathFromQuick(files[i]);                if (tempStr == targetPath)                {                    tempStrs.Add(files[i]);                }            }            return tempStrs;        }        /// <summary>        /// 获取快捷方式的目标文件路径-用于判断是否已经开启了自动启动        /// </summary>        /// <param name="shortcutPath"></param>        /// <returns></returns>        private static string GetAppPathFromQuick(string shortcutPath)        {            //快捷方式文件的路径 = @"d:\Test.lnk";            if (System.IO.File.Exists(shortcutPath))            {                //WshShell shell = new WshShell();                //IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);                var shellType = Type.GetTypeFromProgID("WScript.Shell");                dynamic shell = Activator.CreateInstance(shellType);                var shortcut = shell.CreateShortcut(shortcutPath);                //快捷方式文件指向的路径.Text = 当前快捷方式文件IWshShortcut类.TargetPath;                //快捷方式文件指向的目标目录.Text = 当前快捷方式文件IWshShortcut类.WorkingDirectory;                return shortcut.TargetPath;            }            else            {                return "";            }        }        /// <summary>        /// 根据路径删除文件-用于取消自启时从计算机自启目录删除程序的快捷方式        /// </summary>        /// <param name="path">路径</param>        private static void DeleteFile(string path)        {            FileAttributes attr = System.IO.File.GetAttributes(path);            if (attr == FileAttributes.Directory)            {                Directory.Delete(path, true);            }            else            {                System.IO.File.Delete(path);            }        }        /// <summary>        /// 在桌面上创建快捷方式-如果需要可以调用        /// </summary>        /// <param name="desktopPath">桌面地址</param>        /// <param name="appPath">应用路径</param>        public static void CreateDesktopQuick(string desktopPath = "", string quickName = "", string appPath = "")        {            List<string> shortcutPaths = GetQuickFromFolder(desktopPath, appPath);            //如果没有则创建            if (shortcutPaths.Count < 1)            {                CreateShortcut(desktopPath, quickName, appPath, "软件描述");            }        }        /// <summary>        /// 为当前正在运行的程序创建一个快捷方式。        /// </summary>        /// <param name="lnkFilePath">快捷方式的完全限定路径。</param>        /// <param name="args">快捷方式启动程序时需要使用的参数。</param>        private static void CreateShortcut(string lnkFilePath, string args = "")        {            var shellType = Type.GetTypeFromProgID("WScript.Shell");            dynamic shell = Activator.CreateInstance(shellType);            var shortcut = shell.CreateShortcut(lnkFilePath);            shortcut.TargetPath = Assembly.GetEntryAssembly().Location;            shortcut.Arguments = args;            shortcut.WorkingDirectory = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;            shortcut.Save();        }        /// <summary>        ///  向目标路径创建指定文件的快捷方式        /// </summary>        /// <param name="directory">目标目录</param>        /// <param name="shortcutName">快捷方式名字</param>        /// <param name="targetPath">文件完全路径</param>        /// <param name="description">描述</param>        /// <param name="iconLocation">图标地址</param>        /// <returns>成功或失败</returns>        private static bool CreateShortcut(string directory, string shortcutName, string targetPath, string description = null, string iconLocation = null)        {            try            {                if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);                         //目录不存在则创建                //添加引用 Com 中搜索 Windows Script Host Object Model                string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));          //合成路径                //WshShell shell = new IWshRuntimeLibrary.WshShell();                //IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath);    //创建快捷方式对象                var shellType = Type.GetTypeFromProgID("WScript.Shell");                dynamic shell = Activator.CreateInstance(shellType);                var shortcut = 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();                                                                                //保存快捷方式                return true;            }            catch (Exception ex)            {                string temp = ex.Message;                temp = "";            }            return false;        }        #endregion        #region 注册表方式自启,需要管理员权限        /// <summary>        /// 将本程序设为开启自启        /// </summary>        /// <param name="onOff">自启开关</param>        /// <returns></returns>        public static bool SetAutoStartByReg(bool onOff)        {            bool isOk = false;            string appName = Process.GetCurrentProcess().MainModule.ModuleName;            string appPath = Process.GetCurrentProcess().MainModule.FileName;            isOk = SetAutoStartByReg(onOff, appName, appPath);            return isOk;        }        /// <summary>        /// 将应用程序设为或不设为开机启动        /// </summary>        /// <param name="onOff">自启开关</param>        /// <param name="appName">应用程序名</param>        /// <param name="appPath">应用程序完全路径</param>        public static bool SetAutoStartByReg(bool onOff, string appName, string appPath)        {            bool isOk = true;            //如果从没有设为开机启动设置到要设为开机启动            if (!IsExistKey(appName) && onOff)            {                isOk = SelfRunning(onOff, appName, @appPath);            }            //如果从设为开机启动设置到不要设为开机启动            else if (IsExistKey(appName) && !onOff)            {                isOk = SelfRunning(onOff, appName, @appPath);            }            return isOk;        }        /// <summary>        /// 判断注册键值对是否存在,即是否处于开机启动状态        /// </summary>        /// <param name="keyName">键值名</param>        /// <returns></returns>        private static bool IsExistKey(string keyName)        {            try            {                bool _exist = false;                RegistryKey local = Registry.LocalMachine;                RegistryKey runs = local.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);                if (runs == null)                {                    RegistryKey key2 = local.CreateSubKey("SOFTWARE");                    RegistryKey key3 = key2.CreateSubKey("Microsoft");                    RegistryKey key4 = key3.CreateSubKey("Windows");                    RegistryKey key5 = key4.CreateSubKey("CurrentVersion");                    RegistryKey key6 = key5.CreateSubKey("Run");                    runs = key6;                }                string[] runsName = runs.GetValueNames();                foreach (string strName in runsName)                {                    if (strName.ToUpper() == keyName.ToUpper())                    {                        _exist = true;                        return _exist;                    }                }                return _exist;            }            catch            {                return false;            }        }        /// <summary>        /// 写入或删除注册表键值对,即设为开机启动或开机不启动        /// </summary>        /// <param name="isStart">是否开机启动</param>        /// <param name="exeName">应用程序名</param>        /// <param name="path">应用程序路径带程序名</param>        /// <returns></returns>        private static bool SelfRunning(bool isStart, string exeName, string path)        {            RegistryKey local = Registry.LocalMachine;            RegistryKey key = local.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);            if (key == null)            {                local.CreateSubKey("SOFTWARE//Microsoft//Windows//CurrentVersion//Run");            }            //若开机自启动则添加键值对            if (isStart)            {                key.SetValue(exeName, path);                key.Close();            }            else//否则删除键值对            {                string[] keyNames = key.GetValueNames();                foreach (string keyName in keyNames)                {                    if (keyName.ToUpper() == exeName.ToUpper())                    {                        key.DeleteValue(exeName);                        key.Close();                    }                }            }            return true;        }        #endregion        #region 是否管理员、以管理员启动        public static bool IsAdministrator()        {            bool result;            try            {                WindowsIdentity identity = WindowsIdentity.GetCurrent();                WindowsPrincipal principal = new WindowsPrincipal(identity);                result = principal.IsInRole(WindowsBuiltInRole.Administrator);            }            catch            {                result = false;            }            return result;        }        public static void StartWithAdministrator(Form mainForm)        {            /**             * 当前用户是管理员的时候,直接启动应用程序             * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行             */            //获得当前登录的Windows用户标示            WindowsIdentity identity = WindowsIdentity.GetCurrent();            WindowsPrincipal principal = new WindowsPrincipal(identity);            //判断当前登录用户是否为管理员            if (principal.IsInRole(WindowsBuiltInRole.Administrator))            {                //如果是管理员,则直接运行                Application.Run(mainForm);            }            else            {                //创建启动对象                ProcessStartInfo startInfo = new ProcessStartInfo();                startInfo.UseShellExecute = true;                startInfo.WorkingDirectory = Environment.CurrentDirectory;                startInfo.FileName = Application.ExecutablePath;                //设置启动动作,确保以管理员身份运行                startInfo.Verb = "runas";                try                {                    Process.Start(startInfo);                }                catch                {                    return;                }                //退出                Application.Exit();            }            //以下是通过配置文件的方式            //在 项目 上 添加新项 选择“应用程序清单文件” 然后单击 添加 按钮            //添加后,默认打开app.manifest文件,将:            //< requestedExecutionLevel  level = "asInvoker" uiAccess = "false" />            // 修改为:            //< requestedExecutionLevel level = "requireAdministrator" uiAccess = "false" />            //然后打开 项目属性 ,将 应用程序 标签页中的 资源 中的 清单 修改为新建的 app.manifest。            //重新生成项目,再次打开程序时就会提示 需要以管理员权限运行。        }        #endregion    }}
 |