2017-06-04 100 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直接运行应用程序时,它完美地工作,但启动时自动启动应用程序时有奇怪路径的文件(未找到图像文件))。