C realizes automatic startup setting code sharing

  • 2021-07-09 09:02:39
  • OfStack


 /// <summary>
  ///  Set the program to start up 
  ///  Or cancel the boot 
  /// </summary>
  /// <param name="started"> Set startup or cancel startup </param>
  /// <param name="exeName"> The name of the program in the registry </param>
  /// <param name="path"> Program path for startup </param>
  /// <returns> Is it successful to start or deactivate </returns>
  public static bool runWhenStart(bool started, string exeName, string path)
  {
   RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);// Open a registry subkey 
   if (key == null)// If the item does not exist, the subitem is created 
   {
    key = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
   }
   if (started == true)
   {
    try
    {
     key.SetValue(exeName, path);// Set to boot 
     key.Close();
    }
    catch
    {
     return false;
    }
   }
   else
   {
    try
    {
     key.DeleteValue(exeName);// Cancel startup 
     key.Close();
    }
    catch
    {
     return false;
    }
   }
   return true;
  }

Related articles: