#nullable enable using System; using Microsoft.Win32; namespace ReminderOrganizer.Services { public class AutostartService : IAutostartService { private const string RegistryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; private const string AppName = "ReminderOrganizer"; /// Registry value: quoted exe path + --minimized (start in tray). public static string BuildCommand(string exePath) => $"\"{exePath}\" --minimized"; /// True if the stored command points at this exe (old entries without quotes count too). public static bool PointsTo(string? stored, string? exePath) { if (string.IsNullOrEmpty(stored) || string.IsNullOrEmpty(exePath)) return false; var s = stored.Trim(); if (s.StartsWith("\"")) { var end = s.IndexOf('"', 1); s = end > 0 ? s.Substring(1, end - 1) : s.Trim('"'); } else if (s.EndsWith(" --minimized")) { s = s[..^" --minimized".Length]; } return string.Equals(s, exePath, StringComparison.OrdinalIgnoreCase); } public bool IsAutostartEnabled { get { try { using var key = Registry.CurrentUser.OpenSubKey(RegistryKey, false); return PointsTo(key?.GetValue(AppName) as string, Environment.ProcessPath); } catch { return false; } } } public void ToggleAutostart() { try { using var key = Registry.CurrentUser.OpenSubKey(RegistryKey, true); if (key == null) return; if (IsAutostartEnabled) { key.DeleteValue(AppName, false); } else { var path = Environment.ProcessPath; if (!string.IsNullOrEmpty(path)) { key.SetValue(AppName, BuildCommand(path)); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"[AutostartService] Failed: {ex.Message}"); } } } }