-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStartupManager.cs
More file actions
82 lines (75 loc) · 2.55 KB
/
StartupManager.cs
File metadata and controls
82 lines (75 loc) · 2.55 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System;
using System.Diagnostics;
using Microsoft.Win32;
namespace ScreenGrid
{
/// <summary>
/// Manages Windows startup registration via the current-user Run registry key.
/// </summary>
internal static class StartupManager
{
private const string RunKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
private const string AppName = "ScreenGrid";
/// <summary>Returns true if ScreenGrid is registered to run at Windows startup.</summary>
public static bool IsRegistered()
{
try
{
using var key = Registry.CurrentUser.OpenSubKey(RunKey, false);
return key?.GetValue(AppName) is string;
}
catch (Exception ex)
{
Debug.WriteLine($"StartupManager.IsRegistered error: {ex.Message}");
return false;
}
}
/// <summary>Registers the current exe to run at Windows startup.</summary>
public static void Register()
{
try
{
string exePath = Environment.ProcessPath
?? Process.GetCurrentProcess().MainModule?.FileName
?? throw new InvalidOperationException("Cannot determine exe path");
using var key = Registry.CurrentUser.OpenSubKey(RunKey, true)
?? throw new InvalidOperationException("Cannot open Run registry key");
key.SetValue(AppName, $"\"{exePath}\"");
}
catch (Exception ex)
{
Debug.WriteLine($"StartupManager.Register error: {ex.Message}");
throw;
}
}
/// <summary>Removes the startup registration.</summary>
public static void Unregister()
{
try
{
using var key = Registry.CurrentUser.OpenSubKey(RunKey, true);
if (key?.GetValue(AppName) != null)
key.DeleteValue(AppName, false);
}
catch (Exception ex)
{
Debug.WriteLine($"StartupManager.Unregister error: {ex.Message}");
throw;
}
}
/// <summary>Toggles the startup registration and returns the new state.</summary>
public static bool Toggle()
{
if (IsRegistered())
{
Unregister();
return false;
}
else
{
Register();
return true;
}
}
}
}