/// <summary> /// 修改程序在注冊表中的鍵值 /// </summary> /// <param name="isAuto">true:開機啟動,false:不開機自啟</param> private void AutoStart(bool isAuto = true, bool showinfo = true) { try { if (isAuto == true) { RegistryKey R_local = Registry.CurrentUser;//RegistryKey R_local = Registry.CurrentUser; RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); R_run.SetValue("應用名稱", Application.ExecutablePath); R_run.Close(); R_local.Close(); } else { RegistryKey R_local = Registry.CurrentUser;//RegistryKey R_local = Registry.CurrentUser; RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); R_run.DeleteValue("應用名稱", false); R_run.Close(); R_local.Close(); } } catch (Exception) { if (showinfo) MessageBox.Show("您需要管理員權限修改", "提示"); } }
注:該程序的啟動項設置到HKEY_Current_User 下,推薦。如果想改在HKEY_LOCAL_MACHINE,只需將CurrentUser改為LocalMachine,即
// 添加到 當前登陸用戶的 注冊表啟動項 RegistryKey RKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); RKey.SetValue("AppName", @"C:\AppName.exe"); // 添加到 所有用戶的 注冊表啟動項 RegistryKey RKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); RKey.SetValue("AppName", @"C:\AppName.exe");
