using System.Security; using Microsoft.Win32; using Titano.Core.Diagnostics; namespace Titano.Uploader.Infrastructure; /// "Start with Windows". public interface IStartupRegistration { bool IsEnabled { get; } void SetEnabled(bool enabled); } /// /// HKCU\Software\Microsoft\Windows\CurrentVersion\Run value that starts the uploader in the tray at sign-in. /// The registry stays the source of truth because Task Manager can turn it off. /// public sealed class RunKeyStartupRegistration : IStartupRegistration { private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run"; private const string ValueName = "Titano Uploader"; public bool IsEnabled { get { try { using var key = Registry.CurrentUser.OpenSubKey(RunKey); return key?.GetValue(ValueName) is string { Length: > 0 }; } catch (SecurityException) { return false; } } } private static string Command => $"\"{Environment.ProcessPath}\" {CommandLine.TrayOption}"; public void SetEnabled(bool enabled) { try { using var key = Registry.CurrentUser.CreateSubKey(RunKey, writable: true); if (enabled) key.SetValue(ValueName, Command, RegistryValueKind.String); else key.DeleteValue(ValueName, throwOnMissingValue: false); } catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException) { Log.Warning("startup", "Run key not updated", ex); } } /// Points an existing entry at the current executable (after an update moved it). public void Refresh() { if (IsEnabled) SetEnabled(true); } }