Home > Enterprise >  Delphi service starting method
Delphi service starting method

Time:09-17

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 versus 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. 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.

CodePudding user response:

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?

Not really, no. A start is a start, regardless of when it is issued. However...

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.

The manager can include an extra parameter when it calls StartService(). The service can then enumerate its Param[] property at startup, looking for that parameter.

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.

Yes, there is - using the lpServiceArgVectors parameter of StartService():

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]).

CodePudding user response:

Got it working using Remy's info. My manager program sends a parameter indicating a manual start:

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

Then my service program checks parameters in the OnStart event:

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