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

Viewed 1111

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

Thanks!

2 Answers

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

It can also be done by adding a shortcut to the user's Startup folder:

    private void OnInitialInstall(UpdateManager mgr)
    {
        mgr.CreateShortcutForThisExe();
        mgr.CreateShortcutsForExecutable("MyApp.exe", ShortcutLocation.StartUp, false);
        mgr.CreateShortcutsForExecutable("MyApp.exe", ShortcutLocation.Desktop, false);
        mgr.CreateShortcutsForExecutable("MyApp.exe", ShortcutLocation.StartMenu, false);
        mgr.CreateUninstallerRegistryEntry();
    }
Related