AutoStartHelper.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 MvvmScaffoldFrame48.DLL.SystemTools
  9. {
  10. public class AutoStartHelper
  11. {
  12. /// <summary>
  13. /// 若出现自启动时相对路径异常的情况可以在程序启动时引用如下代码
  14. /// Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
  15. /// </summary>
  16. // 注册表路径
  17. private static readonly string RegistryPath = @"Software\Microsoft\Windows\CurrentVersion\Run";
  18. // 应用名称,作为注册表键名
  19. private static readonly string AppName = "CCDCount";
  20. /// <summary>
  21. /// 获取当前可执行文件路径
  22. /// </summary>
  23. public static string GetExecutablePath()
  24. {
  25. return Process.GetCurrentProcess().MainModule.FileName;
  26. }
  27. /// <summary>
  28. /// 检查是否已设置自启动
  29. /// </summary>
  30. public static bool IsAutoStart()
  31. {
  32. using (var key = Registry.CurrentUser.OpenSubKey(RegistryPath, false))
  33. {
  34. if (key == null) return false;
  35. var value = key.GetValue(AppName);
  36. // 验证路径是否一致,防止exe移动后失效
  37. return value != null && value.ToString() == GetExecutablePath();
  38. }
  39. }
  40. /// <summary>
  41. /// 设置或取消自启动
  42. /// </summary>
  43. /// <param name="isAutoStart">true 为启用,false 为禁用</param>
  44. public static void SetAutoStart(bool isAutoStart)
  45. {
  46. using (var key = Registry.CurrentUser.OpenSubKey(RegistryPath, true))
  47. {
  48. if (key == null) return;
  49. if (isAutoStart)
  50. {
  51. if (!IsAutoStart())
  52. {
  53. key.SetValue(AppName, GetExecutablePath());
  54. }
  55. }
  56. else
  57. {
  58. // false 参数表示值不存在时不抛出异常
  59. key.DeleteValue(AppName, false);
  60. }
  61. }
  62. }
  63. }
  64. }