private static RegistryKey _rlocal = Registry.LocalMachine.CreateSubKey(@"SOFTWAREMicrosoftWindowsCurrentVersionRun"); /// <summary> /// 根据 app.config 中"isAuto",设置是否开机启动 /// </summary> public static void AutoRun() { string appPath = System.Reflection.Assembly.GetExecutingAssembly().Location; //E:CodeXXX.JobRunnerinDebugKMHC.OCP.JobRunner.exe XXX是路径和namespace var appName = appPath.Substring(appPath.LastIndexOf('\') + 1); //XXX.JobRunner.exe XXX 是namespace try { var isAuto = ConfigurationManager.AppSettings["isAuto"]; if (isAuto == "1") { _rlocal.SetValue(appName, string.Format(@"""{0}""", appPath)); } else { _rlocal.DeleteValue(appName, false); } _rlocal.Close(); } catch (Exception ex) { Console.WriteLine(string.Format("设置开机是否启动失败: {0}", ex.Message)); } }
备注:需要开机启动的程序最后设置为管理员权限