How to (un-)install and start a service object
05
Apr
Posted by: Christian Wimmer in: JEDI Windows API Headers
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.
-
TServiceApplicationEx = class(TServiceApplication)
-
public
-
procedure RegisterServices(Install, Silent: Boolean);
-
end;
-
-
{ TServiceApplicationEx }
-
procedure TServiceApplicationEx.RegisterServices(Install, Silent: Boolean);
-
begin
-
inherited;
-
end;
Of course we need a tool function that starts our service
-
uses JwaWindows;procedure StartTheService(Service : TService);
-
var
-
hSCM: SC_HANDLE;
-
hSvc: SC_HANDLE;
-
args: array of PChar;
-
i : Integer;
-
begin
-
hSCM := OpenSCManager(nil, SERVICES_ACTIVE_DATABASEW, SC_MANAGER_CONNECT);
-
if hSCM = 0 then
-
RaiseLastOSError;
-
-
try
-
hSvc := OpenService(hSCM, PChar(Service.Name), SERVICE_START);
-
if hSvc = 0 then
-
RaiseLastOSError; try
-
SetLength(args, ParamCount);
-
-
for i := 0 to ParamCount-1 do
-
begin
-
GetMem(args[i], Length(ParamStr(i+1))+2);
-
StringCchCopy(args[i], Length(ParamStr(i+1))+2, PChar(ParamStr(i+1)));
-
end;
-
-
try
-
if not StartServiceA(hSvc, Length(args), @args[0]) then
-
RaiseLastOSError;
-
finally
-
for i := 0 to ParamCount-1 do
-
begin
-
FreeMem(args[i]);
-
end;
-
end;
-
finally
-
CloseServiceHandle(hSvc);
-
end;
-
finally
-
CloseServiceHandle(hScm);
-
end;
-
end;
Finally we can adjust the main application to install, uninstall or run the service.
-
-
program xy;
-
uses SvcMgr, …;
-
begin
-
SvcMgr.Application.Free;
-
SvcMgr.Application := TServiceApplicationEx.Create(nil);
-
SvcMgr.Application.Initialize;
-
SvcMgr.Application.CreateForm(TMyService, MyService);
-
if <InstallService> then
-
SvcMgr.Application.RegisterServices(true, true)
-
else
-
if <DeInstallService> then
-
SvcMgr.Application.RegisterServices(false, true)
-
else
-
if <StartService> then
-
StartService(MyService)
-
and exit here
-
else
-
SvcMgr.Application.Run;
-
end;
convert this post to pdf.
Leave a reply