2017-06-04 105 views
0

我想讓我的應用程序在用戶登錄(系統啓動)時啓動。 我發現了這樣的解決方案:Windows使應用程序在系統啓動時運行(用戶登錄)

app.manifest

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> 

PreferencesWindows.xaml.cs

if (ServerSettings.ShouldApplicationAutostart) 
    { 
     SystemStartupService.AddThisAppToCurrentUserStartup(); 
    } else 
    { 
     SystemStartupService.DeleteThisAppFromCurrentUserStartup(); 
    } 

SystemStartupService.cs

public static void AddThisAppToCurrentUserStartup() 
     { 
      AddAppToCurrentUserStartup(Assembly.GetExecutingAssembly().GetName().Name, 
             Assembly.GetExecutingAssembly().Location, true); 
     } 

     public static void AddAppToCurrentUserStartup(string appName, string appPath, bool asBackground) { 
      using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true)) 
      { 
       registryKey.SetValue(appName, "\"" + appPath + "\"" + (asBackground ? " /background" : "")); 
      } 
     } 

     public static void DeleteThisAppFromCurrentUserStartup() 
     { 
      DeleteAppFromCurrentUserStartup(Assembly.GetExecutingAssembly().GetName().Name); 
     } 

     public static void DeleteAppFromCurrentUserStartup(string appName) 
     { 
      using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true)) 
      { 
       registryKey.DeleteValue(appName, false); 
      } 
     } 

問題是此解決方案不適用於我的應用程序,我不知道爲什麼。上面的代碼成功添加條目註冊表系統配置>啓動

註冊表編輯器 enter image description here

任務管理enter image description here

如果它的事項,這是在通知試運行簡單的WPF應用程序。

問題:應用程序無法在用戶登錄時啓動!

+0

我想你的appPath是錯誤的。 –

+0

不,這是正確的,當我複製粘貼它指向與.exe文件的目錄。我認爲也許有調試版本的問題,所以我發佈並將其複製到Program Files,並且它也不起作用 –

+0

如果您將正確的文本放入註冊表項中,此工作方式無需任何代碼,因此您唯一可以做錯了就是路徑錯誤或文件無法訪問。 –

回答

0

上述解決方案正常工作。 MainWindow.cs中的代碼中有一些錯誤,導致該應用程序無法正確啓動。此外,它是在OnInitialized()方法中,它可以防止Debugger在app自動運行失敗時顯示此錯誤。這個錯誤與壞的圖標路徑有關(我一直使用Assembly目錄中的加載圖標資源,當從Visual Studio直接運行應用程序時,它完美地工作,但啓動時自動啓動應用程序時有奇怪路徑的文件(未找到圖像文件))。