開發了一個wpf程序,需要管理員權限,設置了requireAdministrator
同時需要開機自啟動,所以添加了注冊表:
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true)) { key.SetValue("MyApp", "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\""); key.Close(); }
但是在設置成功后,在電腦啟動后程序卻沒有自動啟動,找了很多辦法,都不行,最后還是在網上找到了解決方案:
https://stackoverflow.com/questions/37440196/c-sharp-application-not-run-on-startup-startup-impact-not-measured-on-windows
就是當我們程序需要管理員權限時,注冊表不能使用CurrentUser
,需要使用LocalMachine
,如下:
using (RegistryKey key = Registry.LocalMachine
.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.SetValue("MyApp", "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\"");
key.Close();
}