参考下面代码
unit Control;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, StdCtrls, WinSvc;
const
ServiceName='TomDemoService';
type
TfrmMain = class(TForm)
cmdStart: TButton;
cmdStop: TButton;
stsMessage: TStatusBar;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cmdStopClick(Sender: TObject);
procedure cmdStartClick(Sender: TObject);
private
{ Private declarations }
schService:SC_HANDLE;
schSCManager:SC_HANDLE;
ssStatus:TServiceStatus;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.DFM}
procedure TfrmMain.FormCreate(Sender: TObject);
begin
schSCManager:=OpenSCManager(nil,nil,SC_MANAGER_ALL_ACCESS);
if (schSCManager<=0) then
begin
MessageDlg('Tom Lee Demo Service is not installed.',mtError,[mbOk],0);
Application.Terminate;
end;
schService:=OpenService(schSCManager,ServiceName,SERVICE_ALL_ACCESS);
if (schService<=0) then
begin
MessageDlg('Tom Lee Demo Service can not open.',mtError,[mbOk],0);
Application.Terminate;
end;
end;
procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
end;
procedure TfrmMain.cmdStopClick(Sender: TObject);
begin
if ControlService(schService,SERVICE_CONTROL_STOP,ssStatus) then
begin
stsMessage.SimpleText:='Stopping Service Now ';
Sleep(1000);
while (QueryServiceStatus(schService,ssStatus)) do
begin
Application.ProcessMessages;
if ssStatus.dwCurrentState=SERVICE_STOP_PENDING then
begin
stsMessage.SimpleText:=stsMessage.SimpleText+('.');
Sleep(1000);
end
else
break;
end;
if ssStatus.dwCurrentState=SERVICE_STOPPED then
stsMessage.SimpleText:='Service Stop Ok'
else
stsMessage.SimpleText:='Service Stop Fail';
end
else
stsMessage.SimpleText:='Service Stop Fail';
end;
procedure TfrmMain.cmdStartClick(Sender: TObject);
var
Argv
Char;
begin
if StartService(schService,0,Argv) then
begin
stsMessage.SimpleText:='Start Service Now ';
Sleep(1000);
while (QueryServiceStatus(schService,ssStatus)) do
begin
Application.ProcessMessages;
if ssStatus.dwCurrentState=SERVICE_START_PENDING then
begin
stsMessage.SimpleText:=stsMessage.SimpleText+('.');
Sleep(1000);
end
else
break;
end;
if ssStatus.dwCurrentState=SERVICE_RUNNING then
stsMessage.SimpleText:='Service Start Ok'
else
stsMessage.SimpleText:='Service Start Fail';
end
else
stsMessage.SimpleText:='Service Start Fail';
end;
end.