For the past six years I’ve been focused on web applications. My current project, however, has me splitting time between the web and the desktop. Today, I needed to programmatically toggle the Startup Type of my service between Manual and Automatic based on business conditions. Here’s how I did it:
/// <summary> /// This routine updates the start mode of the provided service. /// </summary> /// <param name="serviceName">Name of the service to be updated</param> /// <param name="startMode">Manual or Automatic. This parameter could probably use /// an enum.</param> /// <param name="errorMsg">If applicable, error message assoicated with exception</param> /// <returns>Success or failure. False is returned if service is not found.</returns> public bool ServiceStartModeUpdate(string serviceName, string startMode, out string errorMsg) { uint success = 1; errorMsg = string.Empty; string filter = String.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", serviceName); ManagementObjectSearcher query = new ManagementObjectSearcher(filter); // No match = failed condition if (query == null) return false; try { ManagementObjectCollection services = query.Get(); foreach (ManagementObject service in services) { ManagementBaseObject inParams = service.GetMethodParameters("ChangeStartMode"); inParams["startmode"] = startMode; ManagementBaseObject outParams = service.InvokeMethod("ChangeStartMode", inParams, null); success = Convert.ToUInt16(outParams.Properties["ReturnValue"].Value); } } catch (Exception ex) { errorMsg = ex.Message; throw; } return (success == 0); }
As I’ve been doing a lot with services and windows applications lately, don’t be surprised in up coming posts start moving down this track. Oh yes, I’ve done a lot with custom installers which I’m sure to write about as well.
[...] Home > C#, Desktop, Services > Check Status of Windows Service Previous: Update Service Startup Type [...]
It would be helpful if you could post the code to change the service type if I know the specific service whose service type is to be changed.
@Vicky123 – My apologies but your question confuses me a bit. I think the provide function does just what you want — it changes the service type to manual or automatic based on a service name. Is that what you need?
Thanks,
I have just put this code into the ProjectInstaller_Committed event, so now the Installer can change the StartMode and start it.
So that is great.
Bart
grandioso a delames si rangento ncias con bespa. mosor hestór se tôncion son entre mi minir bismo y peditear frare osomo.