StartupTool.cs 2.8 KB

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