本文介绍了组现有的服务"自动(延时启动)QUOT;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个已经安装 Windows服务在C#中设置为自动延时启动。如何设置一个窗口服务,以

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)

找不到在ServiceStartMode枚举该值

Can't find that value in the ServiceStartMode enum.

编辑: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;
    }
}

这是我怎么称呼它:

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



但没有结果。

But with no result.

推荐答案

。看看调用Windows的的功能,具有 dwInfoLevel SERVICE_CONFIG_DELAYED_AUTO_START_INFO SERVICE_DELAYED_AUTO_START_INFO 结构与 fDelayedAutostart 设置为 TRUE

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

这篇关于组现有的服务&QUOT;自动(延时启动)QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 03:07
查看更多