AutoStartHelper.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 GetExecutablePath()
  20. {
  21. return Process.GetCurrentProcess().MainModule.FileName;
  22. }
  23. /// <summary>
  24. /// 检查是否已设置自启动
  25. /// </summary>
  26. public static bool IsAutoStart()
  27. {
  28. using (var key = Registry.CurrentUser.OpenSubKey(RegistryPath, false))
  29. {
  30. if (key == null) return false;
  31. var value = key.GetValue(AppName);
  32. // 验证路径是否一致,防止exe移动后失效
  33. return value != null && value.ToString() == GetExecutablePath();
  34. }
  35. }
  36. /// <summary>
  37. /// 设置或取消自启动
  38. /// </summary>
  39. /// <param name="isAutoStart">true 为启用,false 为禁用</param>
  40. public static void SetAutoStart(bool isAutoStart)
  41. {
  42. using (var key = Registry.CurrentUser.OpenSubKey(RegistryPath, true))
  43. {
  44. if (key == null) return;
  45. if (isAutoStart)
  46. {
  47. if (!IsAutoStart())
  48. {
  49. key.SetValue(AppName, GetExecutablePath());
  50. }
  51. }
  52. else
  53. {
  54. // false 参数表示值不存在时不抛出异常
  55. key.DeleteValue(AppName, false);
  56. }
  57. }
  58. }
  59. }
  60. }