Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
693 views
in Technique[技术] by (71.8m points)

c# - Set existing service to "Auto (Delayed start)"

I'm trying to set an already installed windows service to automatic delayed start in C#. How do I set a windows service to

Automatic (Delayed Start) 

Can't find that value in the ServiceStartMode enum.

Edit:1

public class ServiceAutoStartInfo
{
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    private struct SERVICE_DELAYED_AUTO_START_INFO
    {

        public bool fDelayedAutostart;
    }

    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool ChangeServiceConfig2(IntPtr hService, int dwInfoLevel, IntPtr lpInfo);

    // Service configuration parameter 
    const int SERVICE_CONFIG_DELAYED_AUTO_START_INFO = 3;

    public bool ChangeDelayedAutoStart(IntPtr hService, bool delayed)
    {


        // Validate service handle
        if (hService != IntPtr.Zero)
        {


            // Create 
            SERVICE_DELAYED_AUTO_START_INFO info = new SERVICE_DELAYED_AUTO_START_INFO();

            // Set the DelayedAutostart property
            info.fDelayedAutostart = delayed;

            // Allocate necessary memory
            IntPtr hInfo = Marshal.AllocHGlobal(Marshal.SizeOf(

            typeof(SERVICE_DELAYED_AUTO_START_INFO)));

            // Convert structure to pointer
            Marshal.StructureToPtr(info, hInfo, true);

            // Change the configuration
            bool result = ChangeServiceConfig2(hService, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, hInfo);

            // Release memory
            Marshal.FreeHGlobal(hInfo);

            return result;
        }

        return false;
    }
}

This is how I call it:

var controller = new ServiceController(s.ServiceName);
var autoDelay = new ServiceAutoStartInfo();
autoDelay.ChangeDelayedAutoStart(controller.ServiceHandle.DangerousGetHandle(), true);

But with no result.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Look into calling the Windows ChangeServiceConfig2 function, with dwInfoLevel of SERVICE_CONFIG_DELAYED_AUTO_START_INFO and a SERVICE_DELAYED_AUTO_START_INFO struct with fDelayedAutostart set to TRUE.

Or, you can do this with the command line:

sc.exe config <servicename> start= delayed-auto

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...