uses
Windows, SvcMgr, WinSvc, Forms, SysUtils,
Unit1 in 'Unit1.pas' {Service1: TService},
Unit2 in 'Unit2.pas' {Form2};
{$R *.RES}
const
SServiceName = 'MyApplication';
{是否install, or uninstall}
function Installing: Boolean;
begin
Result := FindCmdLineSwitch('INSTALL',['-','\','/'], True) or
FindCmdLineSwitch('UNINSTALL',['-','\','/'], True);
end;
function StartService: Boolean;
var
Mgr, Svc: Integer;
begin
Result := False;
Mgr := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
if Mgr <> 0 then
begin //这函数就像在“服务”中启动某个服务一样的作用。
Svc := OpenService(Mgr, PChar(SServiceName), SERVICE_ALL_ACCESS);
Result := Svc <> 0;
CloseServiceHandle(Mgr);
end;
end;
begin
if not Installing then
begin{如果有本程序实例,退出}
CreateMutex(nil, True, 'MyService');
if GetLastError = ERROR_ALREADY_EXISTS then
begin
MessageBox(0, 'Already Running', 'Error', MB_ICONERROR);
Halt;
end;
end;
//如果是出现在“服务”中而且是自动启动,则是下面情况
if Installing and StartService then
begin
SvcMgr.Application.Initialize;
Service1 := TService1.CreateNew(SvcMgr.Application, 0);
SvcMgr.Application.CreateForm(TForm2, Form2);
SvcMgr.Application.Run;
end
else{否则是以Explorer, 双击来启动本程序,则是这种情况}
begin
Forms.Application.Initialize;
Application.CreateForm(TForm2, Form2);
Form2.Initialize;
Application.Run;
end;
end.
//TService服务单元(menus->new->Service Application)
unit Unit1;