AutoStartHelper.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. using Microsoft.Win32;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace CCDCount.DLL.Tools
  9. {
  10. public class AutoStartHelper
  11. {
  12. // 注册表路径
  13. private static readonly string RegistryPath = @"Software\Microsoft\Windows\CurrentVersion\Run";
  14. // 应用名称,作为注册表键名
  15. private static readonly string AppName = "CCDCount";
  16. /// <summary>
  17. /// 获取当前可执行文件路径(带引号,用于注册表)
  18. /// </summary>
  19. public static string GetExecutablePathForRegistry()
  20. {
  21. string path = Process.GetCurrentProcess().MainModule.FileName;
  22. // 如果路径包含空格,必须用双引号包裹
  23. if (path.Contains(" "))
  24. {
  25. return $"\"{path}\"";
  26. }
  27. return path;
  28. }
  29. /// <summary>
  30. /// 获取当前可执行文件路径
  31. /// </summary>
  32. public static string GetExecutablePath()
  33. {
  34. return Process.GetCurrentProcess().MainModule.FileName;
  35. }
  36. /// <summary>
  37. /// 检查是否已设置自启动
  38. /// </summary>
  39. public static bool IsAutoStart()
  40. {
  41. using (var key = Registry.CurrentUser.OpenSubKey(RegistryPath, false))
  42. {
  43. if (key == null) return false;
  44. var value = key.GetValue(AppName);
  45. // 验证路径是否一致,防止exe移动后失效
  46. return value != null && value.ToString() == GetExecutablePath();
  47. }
  48. }
  49. /// <summary>
  50. /// 设置或取消自启动
  51. /// </summary>
  52. /// <param name="isAutoStart">true 为启用,false 为禁用</param>
  53. public static void SetAutoStart(bool isAutoStart)
  54. {
  55. using (var key = Registry.CurrentUser.OpenSubKey(RegistryPath, true))
  56. {
  57. if (key == null) return;
  58. if (isAutoStart)
  59. {
  60. if (!IsAutoStart())
  61. {
  62. key.SetValue(AppName, GetExecutablePathForRegistry());
  63. }
  64. }
  65. else
  66. {
  67. // false 参数表示值不存在时不抛出异常
  68. key.DeleteValue(AppName, false);
  69. }
  70. }
  71. }
  72. private const string TaskName = "CCDCount";
  73. /// <summary>
  74. /// 检查任务是否已注册且处于启用状态
  75. /// </summary>
  76. /// <returns>true: 已注册且启用; false: 未注册或已禁用</returns>
  77. public static bool IsTaskRegisteredAndEnabled()
  78. {
  79. try
  80. {
  81. // 查询任务状态
  82. // /fo LIST 以列表格式输出
  83. // /v 显示详细信息
  84. string arguments = $"/query /tn \"{TaskName}\" /fo LIST /v";
  85. ProcessStartInfo startInfo = new ProcessStartInfo
  86. {
  87. FileName = "schtasks",
  88. Arguments = arguments,
  89. UseShellExecute = false,
  90. RedirectStandardOutput = true,
  91. RedirectStandardError = true,
  92. CreateNoWindow = true
  93. };
  94. using (Process process = Process.Start(startInfo))
  95. {
  96. string output = process.StandardOutput.ReadToEnd();
  97. process.WaitForExit();
  98. if (process.ExitCode == 0)
  99. {
  100. // 检查输出中是否包含 "Status: Ready" 或 "State: Enabled"
  101. // 不同语言版本的Windows输出可能略有不同,通常检查 "Ready" 或 "Enabled"
  102. // 英文系统: "Status: Ready"
  103. // 中文系统: "状态: 就绪"
  104. // 更通用的方法是检查是否存在该任务名,且没有报错
  105. // 如果需要严格判断是否启用,可以解析输出中的 "Status" 行
  106. if (output.Contains("Ready") || output.Contains("就绪"))
  107. {
  108. return true;
  109. }
  110. // 如果任务是 "Disabled" (禁用) 或 "Disabled" (中文: 已禁用),则返回 false
  111. if (output.Contains("Disabled") || output.Contains("已禁用"))
  112. {
  113. return false;
  114. }
  115. // 其他状态视为未准备好
  116. return false;
  117. }
  118. else
  119. {
  120. // 退出码非0,通常意味着任务不存在 (ERROR: The system cannot find the file specified.)
  121. return false;
  122. }
  123. }
  124. }
  125. catch (Exception)
  126. {
  127. // 发生异常时,保守地认为未注册,以便后续尝试重新注册
  128. return false;
  129. }
  130. }
  131. /// <summary>
  132. /// 创建或更新开机自启任务
  133. /// </summary>
  134. public static void RegisterTask()
  135. {
  136. // 1. 先检查是否已经正确配置
  137. if (IsTaskRegisteredAndEnabled())
  138. {
  139. // 可选:进一步检查路径是否一致,如果路径变了也需要更新
  140. // 这里为了简化,如果已启用则直接返回,避免重复弹窗
  141. Console.WriteLine("任务已存在且处于启用状态,无需操作。");
  142. return;
  143. }
  144. try
  145. {
  146. string exePath = Process.GetCurrentProcess().MainModule.FileName;
  147. // 构建 schtasks 命令
  148. // /ru "" 表示以当前用户运行 (在某些Win11版本中,显式指定用户更稳定)
  149. // /rl highest 表示以最高权限运行
  150. // /sc onlogon 表示登录时触发
  151. // /f 强制覆盖已存在的任务
  152. string arguments = $"/create /tn \"{TaskName}\" /tr \"\\\"{exePath}\\\"\" /sc onlogon /rl highest /f";
  153. ProcessStartInfo startInfo = new ProcessStartInfo
  154. {
  155. FileName = "schtasks",
  156. Arguments = arguments,
  157. UseShellExecute = false,
  158. RedirectStandardOutput = true,
  159. RedirectStandardError = true,
  160. Verb = "runas" // 请求管理员权限
  161. };
  162. using (Process process = Process.Start(startInfo))
  163. {
  164. process.WaitForExit();
  165. if (process.ExitCode == 0)
  166. {
  167. Console.WriteLine("任务计划创建/更新成功");
  168. }
  169. else
  170. {
  171. string error = process.StandardError.ReadToEnd();
  172. Console.WriteLine($"创建失败: {error}");
  173. }
  174. }
  175. }
  176. catch (Exception ex)
  177. {
  178. Console.WriteLine($"异常: {ex.Message}");
  179. }
  180. }
  181. /// <summary>
  182. /// 删除开机自启任务
  183. /// </summary>
  184. public static void UnregisterTask()
  185. {
  186. // 可选:先检查是否存在,避免无意义的弹窗
  187. try
  188. {
  189. string checkArgs = $"/query /tn \"{TaskName}\"";
  190. ProcessStartInfo checkInfo = new ProcessStartInfo("schtasks", checkArgs)
  191. {
  192. UseShellExecute = false,
  193. CreateNoWindow = true
  194. };
  195. using (var p = Process.Start(checkInfo))
  196. {
  197. p.WaitForExit();
  198. if (p.ExitCode != 0)
  199. {
  200. Console.WriteLine("任务不存在,无需删除。");
  201. return;
  202. }
  203. }
  204. }
  205. catch { }
  206. try
  207. {
  208. string arguments = $"/delete /tn \"{TaskName}\" /f";
  209. ProcessStartInfo startInfo = new ProcessStartInfo
  210. {
  211. FileName = "schtasks",
  212. Arguments = arguments,
  213. UseShellExecute = false,
  214. RedirectStandardOutput = true,
  215. RedirectStandardError = true,
  216. Verb = "runas"
  217. };
  218. using (Process process = Process.Start(startInfo))
  219. {
  220. process.WaitForExit();
  221. if (process.ExitCode == 0)
  222. {
  223. Console.WriteLine("任务删除成功");
  224. }
  225. else
  226. {
  227. string error = process.StandardError.ReadToEnd();
  228. Console.WriteLine($"删除失败: {error}");
  229. }
  230. }
  231. }
  232. catch (Exception ex)
  233. {
  234. Console.WriteLine($"删除任务失败: {ex.Message}");
  235. }
  236. }
  237. }
  238. }