AppUtil.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using Microsoft.Win32;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows;
  8. namespace DeviceCenter
  9. {
  10. class AppUtil
  11. {
  12. public static bool isAutoStart()
  13. {
  14. string strName = AppDomain.CurrentDomain.BaseDirectory + "DeviceCenter.exe";//获取要自动运行的应用程序名
  15. string strnewName = strName.Substring(strName.LastIndexOf("\\") + 1);//获取应用程序文件名,不包括路径
  16. RegistryKey registry = Registry.LocalMachine.OpenSubKey($"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);//检索指定的子项
  17. if (registry != null)
  18. {
  19. if (strName.Equals(registry.GetValue(strnewName)))
  20. {
  21. return true;
  22. }
  23. }
  24. return false;
  25. }
  26. public static void enableAutoStart()
  27. {
  28. string strName = AppDomain.CurrentDomain.BaseDirectory + "DeviceCenter.exe";//获取要自动运行的应用程序名
  29. if (!System.IO.File.Exists(strName))//判断要自动运行的应用程序文件是否存在
  30. return;
  31. string strnewName = strName.Substring(strName.LastIndexOf("\\") + 1);//获取应用程序文件名,不包括路径
  32. RegistryKey registry = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);//检索指定的子项
  33. if (registry == null)//若指定的子项不存在
  34. registry = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");//则创建指定的子项
  35. registry.SetValue(strnewName, strName);//设置该子项的新的“键值对”
  36. MessageBox.Show("设置完毕");
  37. }
  38. public static void disableAutoStart()
  39. {
  40. string strName = AppDomain.CurrentDomain.BaseDirectory + "DeviceCenter.exe";//获取要自动运行的应用程序名
  41. if (!System.IO.File.Exists(strName))//判断要取消的应用程序文件是否存在
  42. return;
  43. string strnewName = strName.Substring(strName.LastIndexOf("\\") + 1);///获取应用程序文件名,不包括路径
  44. RegistryKey registry = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);//读取指定的子项
  45. if (registry == null)//若指定的子项不存在
  46. registry = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");//则创建指定的子项
  47. registry.DeleteValue(strnewName, false);//删除指定“键名称”的键/值对
  48. MessageBox.Show("设置完毕");
  49. }
  50. }
  51. }