c# 设置程序开机启动 AutoStartHelper
using Microsoft.Win32;
using System;
using System.Reflection;
namespace Boaway.Platform.DataCollection.Client.Helper
{
public static class AutoStartHelper
{
//程序的名称
//public static string SoftWareName = "Raink.KeyPressedView";
public static string SoftWareName = Assembly.GetExecutingAssembly().GetName().Name;
public static void SetStartWithStartUp()
{
string path = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
// 针对当前用户添加注册表启动项
RegistryKey rk = Registry.CurrentUser;
//注册表位置
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
// 检测是否之前有设置自启动了,如果设置了,就看值是否一样
string old_path = (string)rk2.GetValue(SoftWareName);
if (path != old_path)
{
//写入值-避免空格导致问题
rk2.SetValue(SoftWareName, $"\"{path}\"");
//MessageBox.Show("设置开机自启成功", "KeyPressedView");
}
//else
//{
// MessageBox.Show("已设置过开机自启", "KeyPressedView");
//}
rk2.Close();
rk.Close();
}
public static bool ExistStartWithStartUp()
{
string path = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
// 针对当前用户添加注册表启动项
RegistryKey rk = Registry.CurrentUser;
//注册表位置
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
// 检测是否之前有设置自启动了,如果设置了,就看值是否一样
string old_path = (string)rk2.GetValue(SoftWareName);
rk2.Close();
rk.Close();
if (path!=old_path)
{
return false;
}
else
{
return true;
}
}
public static void CancelStartWithStartUp()
{
//string path = AppDomain.CurrentDomain.BaseDirectory;
RegistryKey rk = Registry.CurrentUser;
//相同的注册表位置
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
//获取现有值
//string old_path = (string)rk2.GetValue(SoftWareName);
//删除值
rk2.DeleteValue(SoftWareName, false);
//MessageBox.Show("已取消开启自启", "KeyPressedView");
rk2.Close();
rk.Close();
}
}
}
留待后查,同时方便他人
联系我:renhanlinbsl@163.com
联系我:renhanlinbsl@163.com