Repository navigation
Expand file tree
/
Copy pathAutoStart.cs
More file actions
49 lines (40 loc) · 1.68 KB
/
Copy pathAutoStart.cs
File metadata and controls
49 lines (40 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using Microsoft.Win32;
namespace WinTextCapture;
/// <summary>Adds/removes the app from the per-user Windows startup (HKCU ...\Run).</summary>
internal static class AutoStart
{
private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
private const string ValueName = App.Name;
public static bool IsEnabled() => ReadCommand() is not null;
public static void ReconcileStartup()
{
string? currentCommand = ReadCommand();
string? storedTarget = AutoStartDecision.TargetPath(currentCommand);
bool storedTargetExists = storedTarget is not null && File.Exists(storedTarget);
Apply(AutoStartDecision.EvaluateStartup(currentCommand, Application.ExecutablePath, storedTargetExists));
}
public static void ApplyUserChange(bool enabled)
{
string? currentCommand = ReadCommand();
Apply(AutoStartDecision.EvaluateUserChange(
enabled,
currentCommand,
Application.ExecutablePath));
}
private static string? ReadCommand()
{
using var key = Registry.CurrentUser.OpenSubKey(RunKey);
return key?.GetValue(ValueName) as string;
}
private static void Apply(AutoStartAction action)
{
if (action == AutoStartAction.LeaveAsIs)
return;
using var key = Registry.CurrentUser.CreateSubKey(RunKey, writable: true)
?? throw new InvalidOperationException("The Windows startup registry key could not be opened.");
if (action == AutoStartAction.Write)
key.SetValue(ValueName, $"\"{Application.ExecutablePath}\"");
else
key.DeleteValue(ValueName, throwOnMissingValue: false);
}
}