StartupTool.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //************************************************************************
  2. // https://github.com/yuzhengyang
  3. // author: yuzhengyang
  4. // date: 2017.3.29 - 2017.6.13
  5. // desc: 设为开机启动
  6. // Copyright (c) yuzhengyang. All rights reserved.
  7. //************************************************************************
  8. using Azylee.Core.WindowsUtils.RegisterUtils;
  9. using Azylee.Core.WindowsUtils.ShortcutUtils;
  10. using System;
  11. namespace Azylee.Core.AppUtils
  12. {
  13. /// <summary>
  14. /// 设为开机启动
  15. /// </summary>
  16. public class StartupTool
  17. {
  18. private static string regAll = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
  19. private static string regCurrent = @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run";
  20. private static string commonStartup = Environment.GetFolderPath(Environment.SpecialFolder.CommonStartup);
  21. private static string startup = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
  22. public static bool Register(string name, string file, bool start = true, bool allUser = true)
  23. {
  24. if (start)
  25. {
  26. //注册开机启动注册表项
  27. if (allUser)
  28. {
  29. if (RegisterTool.SetValue(regAll, name, file)) return true;
  30. }
  31. else
  32. {
  33. if (RegisterTool.SetValue(regCurrent, name, file)) return true;
  34. }
  35. }
  36. else
  37. {
  38. //移除开机启动注册表项
  39. if (allUser)
  40. {
  41. if (RegisterTool.DeleteValue(regAll, name)) return true;
  42. }
  43. else
  44. {
  45. if (RegisterTool.DeleteValue(regCurrent, name)) return true;
  46. }
  47. }
  48. return false;
  49. }
  50. public static bool Shortcut(string name, string file, bool start = true, bool allUser = true)
  51. {
  52. if (start)
  53. {
  54. //添加开机启动开始菜单项
  55. if (allUser)
  56. {
  57. if (ShortcutTool.Create(commonStartup, name, file)) return true;
  58. }
  59. else
  60. {
  61. if (ShortcutTool.Create(startup, name, file)) return true;
  62. }
  63. }
  64. else
  65. {
  66. //删除开机启动开始菜单项
  67. if (allUser)
  68. {
  69. if (ShortcutTool.Delete(commonStartup, name)) return true;
  70. }
  71. else
  72. {
  73. if (ShortcutTool.Delete(startup, name)) return true;
  74. }
  75. }
  76. return false;
  77. }
  78. }
  79. }