C# winform设置开机启动
命名空间
using Microsoft.Win32;
代码
注意this.uiCheckBox1.Checked时针对Winfom程序的,如果是命令行程序要另外设置一个触发值
private void cbx_startup()
{
// 要设置软件名称,有唯一性要求,最好起特别一些
string SoftWare = "SunnyNetEaseCloud";
// 注意this.uiCheckBox1.Checked时针对Winfom程序的,如果是命令行程序要另外设置一个触发值
if (this.uiCheckBox1.Checked)
{
Console.WriteLine("设置开机自启动,需要修改注册表", "提示");
string path = Application.ExecutablePath;
RegistryKey rk = Registry.CurrentUser; //
// 添加到 当前登陆用户的 注册表启动项
try
{
//
//SetValue:存储值的名称
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
// 检测是否之前有设置自启动了,如果设置了,就看值是否一样
string old_path = (string)rk2.GetValue(SoftWare);
Console.WriteLine("\r\n注册表值: {0}", old_path);
if (old_path ==null || !path.Equals(old_path))
{
rk2.SetValue(SoftWare, path);
Console.WriteLine("添加开启启动成功");
}
rk2.Close();
rk.Close();
}
catch (Exception ee)
{
Console.WriteLine("开机自启动设置失败");
}
}
else
{
// 取消开机自启动
Console.WriteLine("取消开机自启动,需要修改注册表", "提示");
string path = Application.ExecutablePath;
RegistryKey rk = Registry.CurrentUser;
try
{
// SetValue: 存储值的名称
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
string old_path = (string)rk2.GetValue(SoftWare);
Console.WriteLine("\r\n注册表值: {0}", old_path);
rk2.DeleteValue(SoftWare, false);
Console.WriteLine("取消开启启动成功");
rk2.Close();
rk.Close();
}
catch (Exception ee)
{
//MessageBox.Show(ee.Message.ToString(), "提 示", MessageBoxButtons.OK, MessageBoxIcon.Error); // 提示
Console.WriteLine("取消开机自启动失败");
}
}
}