一、自启动之注册表
添加注册表自启动方法:
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);
}