C#设置程序开机自启动

 /// 
        /// 设置开机自启动
        /// 
        /// 目标名
        /// exe路径
        /// 启动或取消
        /// 
        public static bool SetAutoRun(string keyName, string filePath, bool AddOrCancel)
        {
            try
            {
                RegistryKey Local = Registry.LocalMachine;
                RegistryKey runKey = Local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\");
                if (AddOrCancel)
                {
                    runKey.SetValue(keyName, filePath);
                    Local.Close();
                }
                else
                {
                    if (runKey != null)
                    {
                        runKey.DeleteValue(keyName, false);
                        Local.Close();
                    }
                }
            }
            catch(Exception ex)
            {
                AppLog.Write(ex.ToString(), LogMessageType.Error);
                return false;
            }
            return true;
        }
SetAutoRun("ServiceControl.exe", Application.StartupPath + @"\ServiceControl.exe", true);

SetAutoRun("ServiceControl.exe", Application.StartupPath + @"\ServiceControl.exe", false)

 

你可能感兴趣的:(C#)