C# 根据当前用户是否是管理员设置开机自启动

参考自:https://blog.csdn.net/flyjimi/article/details/6776228

   首先判断当前用户是否是管理员,如果是管理员,则把当前程序添加到本地计算机开机自启动的注册表中;不是管理员的话,则把当前程序添加到当前用户开机自启动的注册表中。同时,可通过删除注册表的方式,取消开机自启动。

        /// <summary>  
        /// 更改是否开机自启动
        /// </summary>  
        /// <param name="isAutoStartup">是否开机自启动</param>  
        public static void ChangeAutoStartUp(bool isAutoStartup)
        {
            string executablePath = Application.ExecutablePath; //可执行文件路径
            string programName = Path.GetFileNameWithoutExtension(executablePath); //程序名称
            //自启动注册表路径
            string registryRunPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
            try
            {
                bool isAdmin = IsAdmin();
                //判断当前用户是否是管理员
                RegistryKey registryKey = isAdmin
                    ? Registry.LocalMachine.CreateSubKey(registryRunPath)
                    : Registry.CurrentUser.CreateSubKey(registryRunPath);
                if (registryKey == null) return;
                if (isAutoStartup)
                {
                    registryKey.SetValue(programName, executablePath); //开启自启动
                }
                else
                {
                    registryKey.DeleteValue(programName, false); //关闭自启动
                }
            }
            catch (Exception e)
            {
                //捕获异常;
            }
        }

        /// <summary>
        /// 判断程序是否以管理员身份运行
        /// </summary>
        /// <returns></returns>
        private static bool IsAdmin()
        {
            bool result = false;
            try
            {
                System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                result = principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
            }
            catch (Exception e)
            {                
                //捕获异常;
            }
            return result;
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值