c#代码实现软件开机自启动

本文介绍了一种使用C#实现的应用程序开机自启动的方法。通过检查当前用户是否为管理员权限,该程序可以将自身添加到或从Windows注册表的开机启动项中移除,确保应用程序能在系统启动时自动运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// LaunchOnBoot是int类型的变量,0:开机不自启;1:开机自启 

   

System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();

        System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);


if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                //如果是管理员,则写入到注册表
                if (LaunchOnBoot == 1)  // 开机自启
                {
                    string path = Application.ExecutablePath;
                    RegistryKey rk = Registry.LocalMachine;
                    RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                    rk2.SetValue("JcShutdown", path);
                    rk2.Close();
                    rk.Close();
                }
                else // 取消开机自启
                {
                    string path = Application.ExecutablePath;
                    RegistryKey rk = Registry.LocalMachine;
                    RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                    rk2.DeleteValue("JcShutdown", false);
                    rk2.Close();
                    rk.Close();
                }
            }
            else
            {
                // 如果不是管理员,则写到当前用户的注册表中去
                if (LaunchOnBoot == 1)  // 开机自启
                {
                    string path = Application.ExecutablePath;
                    RegistryKey rk = Registry.CurrentUser;
                    RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                    rk2.SetValue("JcShutdown", path);
                    rk2.Close();
                    rk.Close();
                }
                else // 取消开机自启
                {
                    string path = Application.ExecutablePath;
                    RegistryKey rk = Registry.CurrentUser;
                    RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                    rk2.DeleteValue("JcShutdown", false);
                    rk2.Close();
                    rk.Close();
                }
            }
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值