-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAutoStartManager.cs
More file actions
100 lines (95 loc) · 2.85 KB
/
AutoStartManager.cs
File metadata and controls
100 lines (95 loc) · 2.85 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using Microsoft.Win32;
namespace InputAutoSwitch
{
/// <summary>
/// 开机自启动管理类
/// </summary>
public static class AutoStartManager
{
private const string APP_NAME = "InputAutoSwitch";
private const string RUN_KEY = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
/// <summary>
/// 检查是否已设置开机自启动
/// </summary>
public static bool IsAutoStartEnabled()
{
try
{
using (RegistryKey? key = Registry.CurrentUser.OpenSubKey(RUN_KEY, false))
{
if (key != null)
{
object? value = key.GetValue(APP_NAME);
return value != null;
}
}
}
catch
{
// 忽略异常
}
return false;
}
/// <summary>
/// 设置开机自启动
/// </summary>
public static bool EnableAutoStart()
{
try
{
string exePath = Application.ExecutablePath;
using (RegistryKey? key = Registry.CurrentUser.OpenSubKey(RUN_KEY, true))
{
if (key != null)
{
key.SetValue(APP_NAME, $"\"{exePath}\"");
return true;
}
}
}
catch (Exception ex)
{
MessageBox.Show($"设置开机自启动失败: {ex.Message}", "错误",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return false;
}
/// <summary>
/// 取消开机自启动
/// </summary>
public static bool DisableAutoStart()
{
try
{
using (RegistryKey? key = Registry.CurrentUser.OpenSubKey(RUN_KEY, true))
{
if (key != null)
{
key.DeleteValue(APP_NAME, false);
return true;
}
}
}
catch (Exception ex)
{
MessageBox.Show($"取消开机自启动失败: {ex.Message}", "错误",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return false;
}
/// <summary>
/// 切换开机自启动状态
/// </summary>
public static void ToggleAutoStart()
{
if (IsAutoStartEnabled())
{
DisableAutoStart();
}
else
{
EnableAutoStart();
}
}
}
}