开机启动

简介: 开机启动

原理

实现

编写 SystemHelper 帮助类,内容如下:

using Microsoft.Win32;
using System;
using System.Windows.Forms;
namespace Project.Helper
{
    public class SystemHelper
    {
        /// <summary>
        /// 注册用户信息
        /// </summary>
        public enum RegistryKeyEnum
        {
            /// <summary>
            /// 当前用户
            /// </summary>
            CurrentUser,
            /// <summary>
            /// 管理员
            /// </summary>
            LocalMachine,
            ClassesRoot,
            Users,
            PerformanceData,
            CurrentConfig
        }
        /// <summary>
        /// 程序开机启动方法
        /// </summary>
        /// <param name="strAppName">应用程序名称</param>
        /// <param name="isAutoRun">是否开机启动</param>
        /// <param name="registryKey">注册表注册到那个用户下,主要是当前用户与管理员的区别</param>
        public static void SetAutoRun(string strAppName, bool isAutoRun, RegistryKeyEnum registryKey = RegistryKeyEnum.CurrentUser)
        {
            try
            {
                RegistryKey reg = registryKey switch
                {
                    RegistryKeyEnum.CurrentUser => Registry.CurrentUser,
                    RegistryKeyEnum.LocalMachine => Registry.LocalMachine,
                    RegistryKeyEnum.ClassesRoot => Registry.ClassesRoot,
                    RegistryKeyEnum.Users => Registry.Users,
                    RegistryKeyEnum.PerformanceData => Registry.PerformanceData,
                    RegistryKeyEnum.CurrentConfig => Registry.CurrentConfig,
                    _ => throw new ArgumentException(message: "用户类型不合法")
                };
                RegistryKey run = reg.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                if (isAutoRun)
                {
                    run.SetValue(strAppName, Application.ExecutablePath);
                }
                else
                {
                    run.DeleteValue(strAppName, false);
                }
                run.Close();
                reg.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
    }
}点击复制复制失败已复制


使用

SystemHelper.SetAutoRun("JX-VCOM", true);  // 注册到普通用户下面
SystemHelper.SetAutoRun("JX-VCOM", true, S
目录
相关文章
|
8月前
|
Ubuntu Linux
ubuntu使用小技巧 -- 设置rclocal开机启动
CentOS下可以通过编辑/etc/rc.local文件,加入一些开机启动项,ubuntu下怎么设置呢?
166 0
|
21天前
|
Unix Linux
# chkconfig: 2345 40 60 是什么
【6月更文挑战第10天】# chkconfig: 2345 40 60 是什么
20 5
|
9月前
|
Linux
一文让你掌握Chkconfig命令的使用
一文让你掌握Chkconfig命令的使用
添加开机启动脚本
添加开机启动脚本
101 0
|
关系型数据库 MySQL Linux
Linux服务开机自启动设置
Linux中也有类似于Window中的开机自启动服务,主要是通过chkconfig命令来设置。它主要用来更新(启动或停止)和查询系统服务的运行级信息。谨记chkconfig不是立即自动禁止或激活一个服务,它只是简单的改变了符号连接。
2516 0
|
JavaScript 前端开发 Shell
|
JavaScript 前端开发 Shell
|
Oracle 关系型数据库 MySQL