我试图在 C# 中将一个已安装 的 Windows 服务设置为自动延迟启动。如何将 Windows 服务设置为
Automatic (Delayed Start)
在 ServiceStartMode 枚举中找不到该值。
编辑: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);
但没有结果。
最佳答案
研究调用 Windows ChangeServiceConfig2
函数,dwInfoLevel
为 SERVICE_CONFIG_DELAYED_AUTO_START_INFO
和 SERVICE_DELAYED_AUTO_START_INFO
结构,fDelayedAutostart
设置为 TRUE
.
或者,您可以使用命令行执行此操作:
sc.exe config <servicename> start= delayed-auto
关于c# - 将现有服务设置为 "Auto (Delayed start)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23270920/