C#实现开机自启动两种方式(注册表、自启动文件夹)

本文介绍了如何使用C#在Windows中通过注册表和自启动文件夹实现程序的开机自动运行,包括添加和删除自启动功能的方法以及代码示例。

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

一、自启动之注册表

  添加注册表自启动方法:

using Microsoft.Win32;
using System.Diagnostics;
  private void AddToAutostart()
        {
            RegistryKey registryKey = Registry.CurrentUser.OpenSubKey
                     ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            // "BaichuiMonitor" 是键的名称,"C:\\YourProgramPath\\YourProgram.exe" 是键值。
            string applicationName = "YourApplicationName"; // 替换为你的应用程序名称  
            if (registryKey.GetValue(applicationName) == null)
            {
                // 如果未设置启动项,则添加一个启动项  
                registryKey.SetValue(applicationName, Application.ExecutablePath);
                Console.WriteLine($"已将 {applicationName} 添加到开机启动项。");
            }
            else
            {
                Console.WriteLine($"{applicationName} 已经在开机启动项中。");
            }

            // 打开系统配置实用程序以查看启动项是否已添加。  
            Process.Start("msconfig");
        }

添加自启动之后可以win+R打开cmd输入regedit命令打开注册表,在注册表的HKEY_LOCAL_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run 路径下可以看见需要自启动的程序

  删除注册表自启动方法:

 private void RemoveFromAutostart()
        {
            RegistryKey registryKey = Registry.CurrentUser.OpenSubKey
         ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            //删除键值
            registryKey.DeleteValue("YourApplicationName");
        }

二、自启动之自启动文件夹

  添加程序快捷方式到自启动文件夹方法 

using Microsoft.Win32;
using System.Diagnostics;
using System.IO;
private void AddToAutostartw()
        {
            ///动态获取程序的相对路径
            string currentDirectory = System.IO.Directory.GetCurrentDirectory();
            //获取自启动文件夹的路径
            string startupFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            string shortcutPath = currentDirectory + "\\YourApplicationName.exe.lnk";
            string destinationPath = Path.Combine(startupFolderPath, "YourApplicationName.exe.lnk");
            File.Copy(shortcutPath, destinationPath, true);
        }

  删除程序在自启动文件夹的快捷方式方法

private void RemoveFromAutostart()
        {
            //获取自启动文件夹的路径
            string startupFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            //注意这里要放入你根目录下程序的快捷方式
            string destinationPath = Path.Combine(startupFolderPath, "YourApplicationName.exe.lnk");
            // 删除快捷方式文件  
            File.Delete(destinationPath);
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

lucky.帅

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

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

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

打赏作者

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

抵扣说明:

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

余额充值