Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...