using Microsoft.Win32;//添加引用
/// <summary>
/// 设置开机启动
/// </summary>
public class AutoRun
{
/// <summary>
/// 开机自启动
/// </summary>
/// <param name="name"></param>
public void SelfRun(string name)
{
try
{
string path = Application.ExecutablePath;\\Winform程序路径
string path = Assembly.GetExecutingAssembly().Location;\\Wpf程序路径
RegistryKey rk = Registry.LocalMachine;
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
rk2.SetValue(name, path);
rk2.Close();
rk.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
/// <summary>
/// 设置开机启动
/// </summary>
/// <param name="name"></param>
/// <param name="path"></param>
public void SetRun(string name, string path)
{
try
{
RegistryKey rk = Registry.LocalMachine;
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
rk2.SetValue(name, path);
rk2.Close();
rk.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
/// <summary>
/// 取消开机启动
/// </summary>
/// <param name="name"></param>
public void RemoveRun(string name)
{
try
{
RegistryKey rk = Registry.LocalMachine;
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
rk2.DeleteValue(name, false);
rk2.Close();
rk.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}