Files
ebbes-meme-clipboard/src/EbbesMemeClipboard/Services/AutostartService.cs
T

43 lines
1.5 KiB
C#

using Microsoft.Win32;
namespace EbbesMemeClipboard.Services;
public sealed class AutostartService : IAutostartService
{
private const string RunKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Run";
private const string ValueName = "EbbesMemeClipboard";
public bool IsEnabled
{
get
{
using var key = Registry.CurrentUser.OpenSubKey(RunKeyPath, writable: false);
return key?.GetValue(ValueName) is string existing && existing.Contains(ExecutablePath, StringComparison.OrdinalIgnoreCase);
}
}
public void SetEnabled(bool enabled)
{
using var key = Registry.CurrentUser.OpenSubKey(RunKeyPath, writable: true)
?? Registry.CurrentUser.CreateSubKey(RunKeyPath, writable: true);
if (enabled)
{
// Quoted because the path can contain spaces, which Windows would otherwise treat
// as an argument boundary and fail to launch.
key.SetValue(ValueName, $"\"{ExecutablePath}\"");
}
else
{
key.DeleteValue(ValueName, throwOnMissingValue: false);
}
}
/// <summary>
/// Environment.ProcessPath, not Assembly.Location: in a single-file published build the
/// managed assemblies are never extracted to disk, so Assembly.Location returns an empty
/// string and the registry entry would point at nothing.
/// </summary>
private static string ExecutablePath => Environment.ProcessPath ?? string.Empty;
}