C# 设置应用程序开机自启动

注册表中设置开机自启动.

将当前应用程序的应用程序文件添加到注册表中,实现开机自启动

using Microsoft.Win32;
using System;

namespace TestAutoRun       
{
    class Program
    {
        static void Main(string[] args)
        {
            //获取当前应用程序.exe的全路径
            string fileName = System.Reflection.Assembly.GetExecutingAssembly().Location;
            SetAutoRun(fileName,true);

            //......
            //程序部分 
            //.....

            Console.WriteLine("执行结束");
            Console.ReadKey();
        }

        /// 
        /// 应用程序开机自启动
        /// 
        /// 
        /// 
        public static void SetAutoRun(string fileName, bool isAutoRun)
        {
            RegistryKey reg = null;
            //设置默认管理员运行
            string admin_path = @"C:\Windows\System32\runas.exe /user:administrator /savecred "; 
            try
            {
                if (!System.IO.File.Exists(fileName))
                    throw new Exception("该文件不存在!");
                string name = fileName.Substring(fileName.LastIndexOf(@"\") + 1);
                name = name.Split('.')[0];
                reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (reg == null)
                    reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                object reg_obj = reg.GetValue(name);

                if (reg_obj != null && reg_obj.ToString().Contains(fileName))
                {
                    if (!isAutoRun)
                        reg.SetValue(name, false);
                }
                else
                {
                    if (isAutoRun)
                    {
                        //reg.SetValue(name, fileName);
                        //设置需要使用默认管理员运行
                        reg.SetValue(name, admin_path + fileName);
                    }
                    else
                        reg.SetValue(name, false);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("设置失败"+ex.StackTrace.ToString());
            }
            finally
            {
                if (reg != null)
                    reg.Close();
            }
        }
    }
}

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