C# 将程序添加到启动项 (写入注册表),及从启动项中删除

  1. #region 将程序添加到启动项  
  2.  /// <summary>  
  3.  /// 注册表操作,将程序添加到启动项  
  4.  /// </summary>  
  5.  public static void SetRegistryApp()  
  6.  {  
  7.      try  
  8.      {  
  9.          Microsoft.Win32.RegistryKey Reg;  
  10.          string ShortFileName = Application.ProductName;  
  11.          Reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", true);  
  12.          if (Reg == null)  
  13.          {  
  14.              Reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run");  
  15.          }  
  16.          Reg.SetValue(ShortFileName, Application.ExecutablePath);  
  17.      }  
  18.      catch (Exception ex)  
  19.      {  
  20.          MessageBox.Show(ex.Message);  
  21.      }  
  22.  }  
  23.  #endregion  
  24.  
  25.  #region 将程序从启动项中删除  
  26.  /// <summary>  
  27.  /// 注册表操作,删除注册表中启动项  
  28.  /// </summary>  
  29.  public static bool DeleteRegisterApp()  
  30.  {  
  31.      string ShortFileName = Application.ProductName;           //获得应用程序名  
  32.   
  33.      try  
  34.      {  
  35.          Microsoft.Win32.RegistryKey Reg;  
  36.          Reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", true);  
  37.          if (Reg == null)  
  38.          {  
  39.              Reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run");  
  40.          }  
  41.          Reg.DeleteValue(ShortFileName, false);  
  42.      }  
  43.      catch (Exception ex)  
  44.      {  
  45.          return false;  
  46.      }  
  47.   
  48.      return true;  
  49.  }  
  50.  #endregion  
  51.   
  52.  /// <summary>  
  53.  ///     检查当前程序是否在启动项中  
  54.  /// </summary>  
  55.  /// <returns></returns>  
  56.  public static bool CheckExistRegisterApp()  
  57.  {  
  58.      string ShortFileName = Application.ProductName;           //获得应用程序名  
  59.      bool bResult = false;  
  60.   
  61.      try  
  62.      {  
  63.          Microsoft.Win32.RegistryKey Reg;  
  64.          Reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", true);  
  65.          if (Reg == null)  
  66.          {  
  67.              Reg = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run");  
  68.          }  
  69.   
  70.          foreach (string s in Reg.GetValueNames())  
  71.          {  
  72.              if (s.Equals(ShortFileName))  
  73.              {  
  74.                  bResult = true;  
  75.                  break;  
  76.              }  
  77.          }  
  78.      }  
  79.      catch (Exception ex)  
  80.      {  
  81.          return false;  
  82.      }  
  83.   
  84.      return bResult;  
  85.  }  
原文地址:https://www.cnblogs.com/2260827114com/p/6410728.html