Search Chirayu Software Solutions Blog

Wednesday, April 30, 2014

Method for changing settings of a Windows Service

  1. /// <summary>
  2. /// method for setting the value of a Windows Service:
  3. /// 2 => Automatic
  4. /// 3 => Manual
  5. /// 4 => Disabled
  6. /// </summary>
  7. /// <param name="serviceName">service we're looking for</param>
  8. /// <param name="value">integer value to set the Start key to</param>
  9. /// <returns></returns>
  10. public bool SetWindowsServiceStatus(string serviceName,int value)
  11. {
  12. try
  13. {
  14. //open the registry key for the specified Windows Service
  15. Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(string.Format(@"SYSTEM\CurrentControlSet\Services\{0}", serviceName), true);
  16. //if exists then set the value to the desired value
  17. if (key != null)
  18. {
  19. /*now set the value of the Start value:
  20. * 2 => Automatic
  21. * 3 => Manual
  22. * 4 => Disabled
  23. * */
  24. key.SetValue("Start", value);
  25. return true;
  26. }
  27. else
  28. {
  29. //not found, so service isnt available or isntalled
  30. throw new Exception(string.Format("The Windows Service {0} could not be located or does not exist", serviceName));
  31. }
  32. }
  33. catch (Exception ex)
  34. {
  35. MessageBox.Show(ex.Message);
  36. return false;
  37. }
  38. }
Post a Comment