简体   繁体   中英

Windows make application to run at system startup (user login)

I am trying to make my application launch at user login (system startup). I found such solution:

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

Problem is that this solution doesn't work for my app and I don't know why. The above code successfully adds entries in registry and System Configuration > Startup

regedit 在此处输入图片说明

TaskManager 在此处输入图片说明

If it matters this is simple wpf application running in notification try.

Problem: Application do not start at user login!

The above solution works correctly. I have some error in code in MainWindow.cs which cause that app couldn't start correctly. Moreover it was in OnInitialized() method which prevents Debugger from showing this error while autorun of app failed. This error was related to bad icon path (I have been using loading Icon resource from Assembly directory which work perfectly while running app directly from Visual Studio but files with odd path (not found image file) when auto launching app at startup).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM