45 lines
1.8 KiB
C#
45 lines
1.8 KiB
C#
using Microsoft.Win32;
|
||
|
||
namespace KronaStaffTerminal.Services;
|
||
|
||
public static class StartupService
|
||
{
|
||
private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
|
||
private const string ValueName = "KronaStaffTerminal";
|
||
|
||
public static void SetEnabled(bool enabled)
|
||
{
|
||
using var key = Registry.CurrentUser.OpenSubKey(RunKey, writable: true)
|
||
?? Registry.CurrentUser.CreateSubKey(RunKey, writable: true);
|
||
if (enabled)
|
||
{
|
||
var executablePath = ResolveExecutablePath();
|
||
key.SetValue(ValueName, $"\"{executablePath}\" --autostart", RegistryValueKind.String);
|
||
}
|
||
else
|
||
{
|
||
key.DeleteValue(ValueName, throwOnMissingValue: false);
|
||
}
|
||
}
|
||
|
||
private static string ResolveExecutablePath()
|
||
{
|
||
var executablePath = Environment.ProcessPath
|
||
?? throw new InvalidOperationException("Не удалось определить путь программы.");
|
||
var debugSegment = $"{Path.DirectorySeparatorChar}Debug{Path.DirectorySeparatorChar}";
|
||
if (!executablePath.Contains(debugSegment, StringComparison.OrdinalIgnoreCase)) return executablePath;
|
||
|
||
var releasePath = executablePath.Replace(
|
||
debugSegment,
|
||
$"{Path.DirectorySeparatorChar}Release{Path.DirectorySeparatorChar}",
|
||
StringComparison.OrdinalIgnoreCase);
|
||
if (File.Exists(releasePath)) return releasePath;
|
||
throw new InvalidOperationException("Автозагрузка доступна после сборки Release-версии программы.");
|
||
}
|
||
|
||
public static bool IsEnabled()
|
||
{
|
||
using var key = Registry.CurrentUser.OpenSubKey(RunKey);
|
||
return key?.GetValue(ValueName) is string;
|
||
}
|
||
}
|