Files
ReminderOrganizer/Services/AutostartService.cs

75 lines
2.4 KiB
C#
Raw Normal View History

#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";
/// <summary>Registry value: quoted exe path + --minimized (start in tray).</summary>
public static string BuildCommand(string exePath) => $"\"{exePath}\" --minimized";
/// <summary>True if the stored command points at this exe (old entries without quotes count too).</summary>
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}");
}
}
}
}