Delphi服务启动方式

Delphi service starting method

我有一个用 Delphi XE5 编写的 Windows 服务应用程序,StartType 设置为 stAuto。该服务是否有办法检测它是在启动时自动启动还是手动启动?我有一个单独的管理器程序来执行安装、启动、停止和卸载。服务需要知道启动是否来自管理器。我可以让经理在手动启动之前创建一个注册表条目,并将其用作我的测试,但想知道是否有更清洁的解决方案。

I have a Windows Service app written in Delphi XE5 with StartType set to stAuto. Is there a way for the service to detect if it started automatically at bootup verses being started manually?

不是,不是。开始就是开始,无论何时发布。然而...

I have a separate manager program that performs the install, start, stop, and uninstall. The service needs to know if the start came from the manager.

管理器在调用 StartService() 时可以包含一个额外的参数。然后,该服务可以在启动时枚举其 Param[] 属性,寻找该参数。

I could have the manager make a registry entry just prior to the manual start and use that as my test but was wondering if there is a cleaner solution.

是的,有 - 使用 StartService()lpServiceArgVectors 参数:

dwNumServiceArgs

The number of strings in the lpServiceArgVectors array. If lpServiceArgVectors is NULL, this parameter can be zero.

lpServiceArgVectors

The null-terminated strings to be passed to the ServiceMain function for the service as arguments. If there are no arguments, this parameter can be NULL. Otherwise, the first argument (lpServiceArgVectors[0]) is the name of the service, followed by any additional arguments (lpServiceArgVectors[1] through lpServiceArgVectors[dwNumServiceArgs-1]).

使用 Remy 的信息成功了。我的manager程序发送一个参数表示手动启动:

arg := 'ManualStart';  // arg: PChar;
StartService(SvcSCH, 1, arg);

然后我的服务程序检查OnStart事件中的参数:

// Param[0] is always set to service name
// Param[1] will not exist if autostart from bootup
ManualStart := (ParamCount > 1) and (Param[1] = 'ManualStart');