using Microsoft.Win32;
|
using Moli.Desktop.Configuration;
|
|
namespace Moli.Desktop.Tray;
|
|
public sealed class RegistryStartupService : IStartupService
|
{
|
private const string RunKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Run";
|
private const string ValueName = "Moli.Desktop";
|
private readonly IConfigurationService _configuration;
|
|
public RegistryStartupService(IConfigurationService configuration)
|
{
|
_configuration = configuration;
|
}
|
|
public bool IsEnabled()
|
{
|
using var key = Registry.CurrentUser.OpenSubKey(RunKeyPath, writable: false);
|
return key?.GetValue(ValueName) is string value && !string.IsNullOrWhiteSpace(value);
|
}
|
|
public async Task SetEnabledAsync(bool enabled, CancellationToken cancellationToken = default)
|
{
|
using var key = Registry.CurrentUser.CreateSubKey(RunKeyPath, writable: true);
|
if (enabled)
|
{
|
var executable = Environment.ProcessPath ?? AppContext.BaseDirectory;
|
key.SetValue(ValueName, $"\"{executable}\"", RegistryValueKind.String);
|
}
|
else
|
{
|
key.DeleteValue(ValueName, throwOnMissingValue: false);
|
}
|
|
var settings = await _configuration.LoadAppSettingsAsync(cancellationToken).ConfigureAwait(false);
|
await _configuration.SaveAppSettingsAsync(
|
settings with { Startup = settings.Startup with { StartWithWindows = enabled } },
|
cancellationToken).ConfigureAwait(false);
|
}
|
}
|