Unfortunately Borland didn’t implement a public register and start function into the class TServiceApplication. So we have to do it ourselves.
First we publish the protected RegisterServices function to allow (un-)install our service(s) programmatically.

  1. TServiceApplicationEx = class(TServiceApplication)
  2. public
  3.   procedure RegisterServices(Install, Silent: Boolean);
  4. end;
  5.  
  6. { TServiceApplicationEx }
  7. procedure TServiceApplicationEx.RegisterServices(Install, Silent: Boolean);
  8. begin
  9.   inherited;
  10. end;

Of course we need a tool function that starts our service

  1. uses JwaWindows;procedure StartTheService(Service : TService);
  2. var
  3.   hSCM: SC_HANDLE;
  4.   hSvc: SC_HANDLE;
  5.   args: array of PChar;
  6.   i : Integer;
  7. begin
  8.   hSCM := OpenSCManager(nil, SERVICES_ACTIVE_DATABASEW, SC_MANAGER_CONNECT);
  9.   if hSCM = 0 then
  10.    RaiseLastOSError;
  11.  
  12. try
  13.     hSvc := OpenService(hSCM, PChar(Service.Name), SERVICE_START);
  14.     if hSvc = 0 then
  15.       RaiseLastOSError;    try
  16.       SetLength(args, ParamCount);
  17.  
  18.       for i := 0 to ParamCount-1 do
  19.       begin
  20.         GetMem(args[i], Length(ParamStr(i+1))+2);
  21.         StringCchCopy(args[i], Length(ParamStr(i+1))+2, PChar(ParamStr(i+1)));
  22.       end;
  23.  
  24.       try
  25.         if not StartServiceA(hSvc, Length(args), @args[0]) then
  26.           RaiseLastOSError;
  27.       finally
  28.         for i := 0 to ParamCount-1 do
  29.         begin
  30.           FreeMem(args[i]);
  31.         end;
  32.       end;
  33.     finally
  34.       CloseServiceHandle(hSvc);
  35.     end;
  36.   finally
  37.     CloseServiceHandle(hScm);
  38.   end;
  39. end;

Finally we can adjust the main application to install, uninstall or run the service.

  1.  
  2. program xy;
  3. uses SvcMgr, …;
  4. begin
  5.   SvcMgr.Application.Free;
  6.   SvcMgr.Application := TServiceApplicationEx.Create(nil);
  7.   SvcMgr.Application.Initialize;
  8.   SvcMgr.Application.CreateForm(TMyService, MyService);
  9.   if <InstallService> then
  10.     SvcMgr.Application.RegisterServices(true, true)
  11.   else
  12.   if <DeInstallService> then
  13.     SvcMgr.Application.RegisterServices(false, true)
  14.   else
  15.   if <StartService> then
  16.     StartService(MyService)
  17.     and exit here
  18.   else
  19.     SvcMgr.Application.Run;
  20. end;
Send post as PDF to www.pdf24.org
convert this post to pdf.