Internet Access: Client Service - The service application code
(Page 2 of 4 )
So far we have looked at what a service is and how it works. Now we will write the code to make our service active. Before we write the code, let's look at what we want our service to do.
Basically we want it to see if the client application is running. If it is not, then we want it to start the application, otherwise we want it to do nothing. The service must check every couple of seconds or minutes (depending on your choice) to see if the client application is active.
Below is the entire service application code. Note that I’ve now saved the unit as “icstarter.” I’ve also added a timer component. The following properties are set:
Displayname: iCafeService
Servicetype: stWin32
Starttype: stAuto
Interactive: True (for debugging purposes)
unit icstarter;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs,
ExtCtrls,shellapi;
type
TService1 = class(TService)
Timer1: TTimer;
procedure Timer1Timer(Sender: TObject);
procedure ServiceExecute(Sender: TService);
private
{ Private declarations }
public
function GetServiceController: TServiceController; override;
{ Public declarations }
end;
var
Service1: TService1;
implementation
{$R *.DFM}
procedure ServiceController(CtrlCode: DWord); stdcall;
begin
Service1.Controller(CtrlCode);
end;
function TService1.GetServiceController: TServiceController;
begin
Result := ServiceController;
end;
procedure TService1.ServiceExecute(Sender: TService);
begin
//activate the client application here
timer1.Enabled:=true;
while not terminated do
servicethread.ProcessRequests(true);
timer1.Enabled:=false;
end;
procedure TService1.Timer1Timer(Sender: TObject);
var
handle,h: HWND;
begin
handle:= FindWindow('TForm1', 'iClient');
if handle > 0 then
begin
showmessage('found it!');
end
else
begin
//startup the app here. Shellexec
shellexecute(h,'open','c:\intertimer\client\iclient.exe',nil,nil,0);
end;
end;
end.
Next: Code Explained >>
More Delphi-Kylix Articles
More By David Web