We know that most services operations can be implemented through ServiceController, including opening, stopping, pausing, and obtaining service status. However, it seems that ServiceController is not easy to do with the modification of services to Startup type. We can do this:
using System;
using ;
using ;
using ;
using ;
namespace ServicesStartup
{
class Program
{
public enum StartupType
{
Automatic,
Disabled,
Manual
}
public static void SetStartupType(string serviceName, StartupType startupType)
{
string type = ();
try
{
ManagementPath mp = new ManagementPath(("Win32_Service.Name='{0}'", serviceName));
if (mp != null)
{
using (ManagementObject mo = new ManagementObject(mp))
{
object[] parameters = new object[1] { type };
("ChangeStartMode", parameters);
}
}
}
catch (ManagementException ex)
{
("An error occured while trying to searching the WMI method: " + ());
}
}
static void Main(string[] args)
{
SetStartupType("gupdate", );
();
}
}
}
The ManagementPath class is used above, or you can do this:
using System;
using ;
using ;
using ;
using ;
namespace ServicesStartup
{
class Program
{
static void Main(string[] args)
{
try
{
ManagementObject classInstance = new ManagementObject("root\\CIMV2",
"Win32_Service.Name='gupdate'", null);
// Obtain in-parameters for the method.
ManagementBaseObject inParams = ("ChangeStartMode");
// Add the input parameters.
inParams["StartMode"] = "Automatic";
// Execute the method and obtain the return values.
ManagementBaseObject outParams = ("ChangeStartMode", inParams, null);
// List outParams
("Out parameters:");
("ReturnValue: " + outParams["ReturnValue"]);
}
catch (ManagementException err)
{
("An error occured while trying to execute the WMI emthod: " + ());
}
();
}
}
}
This code uses the ManagementObject class, and the output ReturnValue is a flag. If the value is 0, the modification is successful.
One thing to note here: C# must be run with administrator permissions to achieve results, otherwise the service startmode modification will have no effect.