1 /// <summary> 2 /// 修改程序在注册表中的键值 3 /// </summary> 4 /// <param name="isAuto">true:开机启动,false:不开机自启</param> 5 private void AutoStart(bool isAuto = true, bool showinfo = true) 6 { 7 try 8 { 9 if (isAuto == true) 10 { 11 RegistryKey R_local = Registry.CurrentUser;//RegistryKey R_local = Registry.CurrentUser; 12 RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); 13 R_run.SetValue("应用名称", Application.ExecutablePath); 14 R_run.Close(); 15 R_local.Close(); 16 } 17 else 18 { 19 RegistryKey R_local = Registry.CurrentUser;//RegistryKey R_local = Registry.CurrentUser; 20 RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); 21 R_run.DeleteValue("应用名称", false); 22 R_run.Close(); 23 R_local.Close(); 24 } 25 } 26 catch (Exception) 27 { 28 if (showinfo) 29 MessageBox.Show("您需要管理员权限修改", "提示"); 30 } 31 }
注:该程序的启动项设置到HKEY_Current_User 下,推荐。如果想改在HKEY_LOCAL_MACHINE,只需将CurrentUser改为LocalMachine,即
1// 添加到 当前登陆用户的 注册表启动项 2RegistryKey RKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); 3RKey.SetValue("AppName", @"C:\AppName.exe"); 4 5// 添加到 所有用户的 注册表启动项 6RegistryKey RKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); 7RKey.SetValue("AppName", @"C:\AppName.exe");