Windows使应用程序在系统启动时运行(用户登录)

时间:2017-06-04 11:01:44

标签: c# .net wpf

我正在尝试在用户登录(系统启动)时启动应用程序。 我找到了这样的解决方案:

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);
            }
        }

问题是这个解决方案对我的应用程序不起作用,我不知道为什么。上述代码成功添加了注册表系统配置&gt;中的条目。启动

注册表编辑器 enter image description here

任务管理 enter image description here

如果重要,这是在通知中运行的简单wpf应用程序试试。

问题:应用程序无法从用户登录开始!

1 个答案:

答案 0 :(得分:0)

以上解决方案正常运行。我在MainWindow.cs中的代码中有一些错误导致该应用程序无法正常启动。此外,它是在OnInitialized()方法中,它阻止调试器在自动运行应用程序失败时显示此错误。此错误与错误的图标路径有关(我一直在使用从程序集目录中加载图标资源,它可以直接从Visual Studio运行应用程序,但在启动时自动启动应用程序时使用奇数路径(未找到图像文件)的文件)。

相关问题