JackMcSlay

I'm creating a service manager and installer for a specific group of services but I need all of them to start manually, but some of them always aways install on automatic. I've already searched around, but I'm out of luck because all I've found is how to create a service with a custom StartType, none on how to change an existing one.


Re: Visual C# General Changing StartType of an existing service

TaylorMichaelL

So you want to change the start mode (Service type is different) of a service that is already installed In this case you need to modify the existing service.

The problem is that .NET does not allow you to change an existing service. You can uninstall and reinstall (with the new start type) through ServiceInstaller but that is probably not what you want. Instead you'll have to P/Invoke out to the SCM. Fortunately it is pretty straightforward. First you need to get the service handle. Then you can call ChangeServiceConfig to change the values you want to change. Most changes take effect immediately.

Here is some sample code to change the start mode of the service. Notice that the handle is already available from .NET so you can use .NET to find the service and then use P/Invoke to change it. Note also that you can change any of the attributes associated with a service or switch to ChangeServiceConfig2 to add some more options.

Code Snippet

[DllImport("kernel32.dll", SetLastError = true)]

[return: MarshalAs(UnmanagedType.Bool)]

private static extern bool ChangeServiceConfig ( SafeHandle hService, uint dwServiceType, uint dwStartType,

uint dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, out uint lpdwTagId,

string lpDependencies, string lpServiceStartName, string lpPassword, string lpDisplayName );

private const uint SERVICE_NO_CHANGE = 0xFFFFFFFF;

private const uint SERVICE_BOOT_START = 0;

private const uint SERVICE_SYSTEM_START = 1;

static void ChangeStartType ( ServiceController svc, ServiceStartMode mode )

{

uint nTag;

ChangeServiceConfig(svc.ServiceHandle, SERVICE_NO_CHANGE, (uint)mode, SERVICE_NO_CHANGE,

null, null, out nTag, null, null, null, null);

}

Michael Taylor - 4/30/07

http://p3net.mvps.org