windowswindows-installersquirrel.windows

How do I register an app to run on Windows startup using Squirrel.Windows?


Is there a way to register an installed app to run on Windows startup when using Squirrel.Windows to build the installer?

Thanks!


Solution

  • I just found out about Custom Squirrel Events and we can handle those to create/remove the appropriate registry for our app to run at windows startup.

    using Microsoft.Win32;
    using Squirrel;
    using System.IO;
    
    public static class UpdateManagerExtensions
    {
        private static RegistryKey OpenRunAtWindowsStartupRegistryKey() =>
            Registry.CurrentUser.OpenSubKey(
                "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
    
        public static void CreateRunAtWindowsStartupRegistry(this UpdateManager updateManager)
        {
            using (var startupRegistryKey = OpenRunAtWindowsStartupRegistryKey())
                startupRegistryKey.SetValue(
                    updateManager.ApplicationName, 
                    Path.Combine(updateManager.RootAppDirectory, $"{updateManager.ApplicationName}.exe"));
        }
    
        public static void RemoveRunAtWindowsStartupRegistry(this UpdateManager updateManager)
        {
            using (var startupRegistryKey = OpenRunAtWindowsStartupRegistryKey())
                startupRegistryKey.DeleteValue(updateManager.ApplicationName);
        }
    }
    

    Use case

    string updateUrl = //...
    
    using (var mgr = new UpdateManager(updateUrl)))
    {
        SquirrelAwareApp.HandleEvents(
            onInitialInstall: v => 
            {
                mgr.CreateShortcutForThisExe();
                mgr.CreateRunAtWindowsStartupRegistry();
            },
            onAppUninstall: v =>
            {
                mgr.RemoveShortcutForThisExe();
                mgr.RemoveRunAtWindowsStartupRegistry();
            });
    }