C# 開機自啟動
阿新 • • 發佈:2018-12-27
using Microsoft.Win32;//新增名稱空間
/// <summary> /// 設定開機自啟動__寫入登錄檔 /// </summary> /// <returns></returns> public static bool SetSelfStarting() { try { string exeDir = Application.ExecutablePath;//要啟動的程式絕對路徑 RegistryKey rk = Registry.LocalMachine; RegistryKey softWare = rk.OpenSubKey("SOFTWARE"); RegistryKey microsoft = softWare.OpenSubKey("Microsoft"); RegistryKey windows = microsoft.OpenSubKey("Windows"); RegistryKey current = windows.OpenSubKey("CurrentVersion"); RegistryKey run = current.OpenSubKey(@"Run", true);//這裡必須加true就是得到寫入許可權 run.SetValue("自己起個名字", exeDir); return true; } catch (Exception ex) { Console.WriteLine(ex.ToString()); return false; } } /// <summary> /// 取消開機自啟__刪除登錄檔 /// </summary> /// <returns></returns> public static bool CancelSelfStarting() { try { RegistryKey rk = Registry.LocalMachine; RegistryKey softWare = rk.OpenSubKey("Software"); RegistryKey microsoft = softWare.OpenSubKey("Microsoft"); RegistryKey windows = microsoft.OpenSubKey("Windows"); RegistryKey current = windows.OpenSubKey("CurrentVersion"); RegistryKey run = current.OpenSubKey(@"Run", true); run.DeleteValue("自己起的名字");//刪除myPro的值 return true; } catch (Exception ex) { Console.WriteLine(ex.ToString()); return false; } }
【設定開機自啟動】
using Microsoft.Win32;//新增名稱空間 public static bool SetAutoRun(string keyName,string filePath) { try { RegistryKey runKey=Registry.LocalMachine.OpenSubKey(@"\SOFTWARE\Microsoft\Windows\CurrentVersion\Run",true); runKey.SetValue(keyName,filePath); runKey.Close(); }catch { return false; } return true; }
【取消開機自啟動】
using Microsoft.Win32;//新增名稱空間 public static bool DeleteAutoRun(string keyName,string filePath) { try { RegistryKey runKey=Registry.LocalMachine.OpenSubKey(@"\SOFTWARE\Microsoft\Windows\CurrentVersion\Run",true); runKey.DeleteValue(keyName,filePath); runKey.Close(); } catch { return false; } return true; }