最近一個C/S項目客戶要求開機自啟的功能,網上找了一些方法,不頂用;最后自己去翻書,找到了這段代碼,親測可用,Wpf環境下需要改下獲取程序目錄的方式即可,Winform直接可用。
1 #region 設置開機自啟2 string strName = AppDomain.CurrentDomain.BaseDirectory + "AutoRunPro.exe";//獲取要自動運行的應用程序名3 if (!System.IO.File.Exists(strName))//判斷要自動運行的應用程序文件是否存在4 return;5 string strnewName = strName.Substring(strName.LastIndexOf("\\") + 1);//獲取應用程序文件名,不包括路徑6 RegistryKey registry = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);//檢索指定的子項7 if (registry == null)//若指定的子項不存在8 registry = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");//則創建指定的子項9 registry.SetValue(strnewName, strName);//設置該子項的新的“鍵值對” 10 11 if (MessageBox.Show("設置完畢") == DialogResult.OK) 12 { 13 RefreshSystem();//刷新系統 14 } 15 #endregion
1 #region 取消開機自啟2 string strName = AppDomain.CurrentDomain.BaseDirectory + "AutoRunPro.exe";//獲取要自動運行的應用程序名3 if (!System.IO.File.Exists(strName))//判斷要取消的應用程序文件是否存在4 return;5 string strnewName = strName.Substring(strName.LastIndexOf("\\") + 1);///獲取應用程序文件名,不包括路徑6 RegistryKey registry = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);//讀取指定的子項7 if (registry == null)//若指定的子項不存在8 registry = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");//則創建指定的子項9 registry.DeleteValue(strnewName, false);//刪除指定“鍵名稱”的鍵/值對 10 if (MessageBox.Show("設置完畢") == DialogResult.OK) 11 { 12 RefreshSystem(); 13 } 14 #endregion