C# 使用注册表开机自启

Windows下常用的开机自启方式有:

1.添加快捷方式到Windows 自启目录下

2.使用注册表添加自启项

3.通过服务的方式启动程序

第一种和第三种 可以参考我的另一篇文章,有介绍有Demo

开机自启,以Windows服务的方式去启动桌面应用程序_一台设备带windows封闭系统,自动运行app,如何进入系统桌面-CSDN博客

这篇文章主要介绍第二种,注册表添加自启项

下边是功能的实现代码:

using Microsoft.Win32;

namespace WPFClient.Tools
{
    /// <summary>
    /// 自启管理
    /// </summary>
    public class StartupManager
    {
        private const string KeyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
        private readonly string _appName = "ClientApp"; // 唯一应用标识

        /// <summary>
        /// 启用自启动
        /// </summary>
        public void EnableStartup()
        {
            using (RegistryKey key = Registry.CurrentUser.OpenSubKey(KeyPath, true))
            {
                // 替换 Application.ExecutablePath 为正确的获取可执行文件路径方式
                // 添加参数可以用来区分 是系统自启还是直接双击exe启动
                string exePath = System.Reflection.Assembly.GetEntryAssembly().Location + " /startup"; // 添加参数
                key.SetValue(_appName, exePath);
            }
        }

        /// <summary>
        /// 禁用自启动
        /// </summary>
        public void DisableStartup()
        {
            using (RegistryKey key = Registry.CurrentUser.OpenSubKey(KeyPath, true))
            {
                if (key.GetValue(_appName) != null)
                {
                    key.DeleteValue(_appName);
                }
            }
        }

        /// <summary>
        /// 检查状态
        /// </summary>
        /// <returns></returns>
        public bool IsStartupEnabled()
        {
            using (RegistryKey key = Registry.CurrentUser.OpenSubKey(KeyPath, false))
            {
                return key?.GetValue(_appName) != null;
            }
        }
    }
}

使用时,先判断是否有自启的状态了,再来处理自启或关闭自启

 //开机自启操作
 if (IsAutoStart)
 {
     StartupManager startupManager = new StartupManager();
     if (!startupManager.IsStartupEnabled())
     {
         startupManager.EnableStartup();
     }
 }
 else
 {
     StartupManager startupManager = new StartupManager();
     if (startupManager.IsStartupEnabled())
     {
         startupManager.DisableStartup();
     }
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rotion_深

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值