C# 实现开机自启动(两种方式,1、写入注册表,2、将程序快捷方式放在系统自启动路径下)
1、路径相关
//程序的完整路径 string appPath = Process.GetCurrentProcess().MainModule.FileName; //操作系统的自启动目录 string sysAutoStartPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup); //获取程序名称带后缀 string appName = Path.GetFileName(appPath);
2、代码封装
/************************************************* * 描述: * * Author:ys * Date:2023/10/27 13:35:39 * Update: * ************************************************/ using IWshRuntimeLibrary; using Microsoft.Win32; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; namespace DbOperTimer.Helper { /// <summary> /// 开机自启动封装 /// </summary> public class AutoPCHelper { #region 方法1 把程序的快捷方式放到windows的自启动目录下 /// <summary> /// 将本程序设为开启自启(Windows自启动路径下) /// </summary> /// <param name="onOff">true为开机自启,false为关闭开机自启</param> /// <param name="errMsg"></param> /// <returns></returns> public static bool SetMeStartByAutoStartPath(bool onOff, out string errMsg) { bool result = false; errMsg = string.Empty; try { //程序的完整路径 string appPath = Process.GetCurrentProcess().MainModule.FileName; //操作系统的自启动目录 string sysAutoStartPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup); //获取程序名称带后缀 string appName = Path.GetFileName(appPath); //设置自启动 if (onOff == true) { result = ShortCutCreate(appName, appPath, sysAutoStartPath, out errMsg); } else { result = ShortCutDelete(appPath, sysAutoStartPath, out errMsg); } return true; } catch (Exception ex) { errMsg = ex.Message + ex.StackTrace; return false; } } /// <summary> /// 获取指定文件夹下的所有快捷方式(不包括子文件夹) /// </summary> /// <param target="">目标文件夹(绝对路径)</param> /// <returns></returns> public static List<string> GetDirectoryFileList(string target) { List<string> list = new List<string>(); list.Clear(); string[] files = Directory.GetFiles(target, "*.lnk"); if (files == null || files.Length == 0) { return list; } for (int i = 0; i < files.Length; i++) { list.Add(files[i]); } return list; } /// <summary> /// 获取快捷方式中的目标(可执行文件的绝对路径) /// </summary> /// <param name="shortCutPath">快捷方式的绝对路径</param> /// <returns></returns> public static string GetAppPathViaShortCut(string shortCutPath) { try { WshShell shell = new WshShell(); IWshShortcut shortct = (IWshShortcut)shell.CreateShortcut(shortCutPath); //快捷方式文件指向的路径.Text = 当前快捷方式文件IWshShortcut类.TargetPath; //快捷方式文件指向的目标目录.Text = 当前快捷方式文件IWshShortcut类.WorkingDirectory; return shortct.TargetPath; } catch { return null; } } /// <summary> /// 判断快捷方式是否存在 /// </summary> /// <param name="path">快捷方式目标(可执行文件的绝对路径)</param> /// <param name="target">快捷方式所在目录(绝对路径)</param> /// <returns></returns> public static bool ShortCutExist(string path, string target) { bool Result = false; List<string> list = GetDirectoryFileList(target); foreach (var item in list) { if (path == GetAppPathViaShortCut(item)) { Result = true; } } return Result; } /// <summary> /// 删除快捷方式(通过快捷方式目标进行删除) /// </summary> /// <param name="appPath">程序所在完整路径</param> /// <param name="sysAutoStartPath">操作系统自启动路径(快捷方式所在目录)</param> /// <param name="errMsg"></param> /// <returns></returns> public static bool ShortCutDelete(string appPath, string sysAutoStartPath, out string errMsg) { bool result = false; errMsg = string.Empty; try { List<string> list = GetDirectoryFileList(sysAutoStartPath); foreach (var item in list) { if (appPath == GetAppPathViaShortCut(item)) { System.IO.File.Delete(item); result = true; } } } catch (Exception ex) { errMsg = ex.Message + ex.StackTrace; result = false; } return result; } /// <summary> /// 创建快捷方式 /// </summary /// <param name="name">快捷方式名称</param> /// <param name="appPath">程序所在完整路径</param> /// <param name="sysAutoStartPath">操作系统自启动路径(只需将程序快捷方式放在此路径即可)</param> /// <returns></returns> public static bool ShortCutCreate(string name, string appPath, string sysAutoStartPath, out string errMsg) { errMsg = string.Empty; bool Result = false; try { // 判断快捷方式是否存在 if (ShortCutExist(appPath, sysAutoStartPath) == true) { return false; } // 如果文件夹不存在则创建 if (!Directory.Exists(sysAutoStartPath)) Directory.CreateDirectory(sysAutoStartPath); // 快捷方式的路径 string ShortCutPath = Path.Combine(sysAutoStartPath, string.Format("{0}.lnk", name)); // 创建快捷方式对象 WshShell Shell = new WshShell(); IWshShortcut ShortCut = (IWshShortcut)Shell.CreateShortcut(ShortCutPath); // 设置快捷方式目标路径 ShortCut.TargetPath = appPath; // 设置快捷方式目标文件夹 ShortCut.WorkingDirectory = Path.GetDirectoryName(appPath); // 设置运行方式,默认为常规窗口 ShortCut.WindowStyle = 1; // 保存快捷方式 ShortCut.Save(); Result = true; } catch (Exception ex) { errMsg = ex.Message + ex.StackTrace; Result = false; } return Result; } #endregion #region 方法2 注册表方式(得有管理员权限) /// <summary> /// 将本程序设为开启自启(注册表方式) /// </summary> /// <param name="isOnOff">自启开关</param> /// <returns></returns> public static bool SetMeStartByRegistry(bool isOnOff, out string srrMsg) { bool isOk = false; string appName = Process.GetCurrentProcess().MainModule.ModuleName; string appPath = Process.GetCurrentProcess().MainModule.FileName; isOk = SetAutoStartByRegistry(isOnOff, appName, appPath, out srrMsg); return isOk; } /// <summary> /// 将应用程序设为或不设为开机启动(注册表方式) /// </summary> /// <param name="isOnOff">自启开关</param> /// <param name="appName">应用程序名</param> /// <param name="appPath">应用程序完全路径</param> public static bool SetAutoStartByRegistry(bool isOnOff, string appName, string appPath, out string errMsg) { errMsg = string.Empty; bool isOk = true; //如果从没有设为开机启动设置到要设为开机启动 if (!IsExistKey(appName) && isOnOff) { isOk = SelfRunning(isOnOff, appName, @appPath, out errMsg); } //如果从设为开机启动设置到不要设为开机启动 else if (IsExistKey(appName) && !isOnOff) { isOk = SelfRunning(isOnOff, appName, @appPath, out errMsg); } 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, out string errMsg) { errMsg = string.Empty; try { 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(); } } } } catch (Exception ex) { errMsg = ex.Message; return false; //throw; } return true; } #endregion } }