用delphi如何启动一个服务?
用delphi如何启动或者停止一个服务?
我需要的是启动或者停止一个已经存在的服务,
谢谢。
[解决办法]
完整的代码,编译通过,如果还有问题,我就要杀人了。
- Delphi(Pascal) code
unit Unit1;interfaceuses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, WinSvc, StdCtrls;type TForm1 = class(TForm) btnStart: TButton; procedure btnStartClick(Sender: TObject); private { Private declarations } public { Public declarations } end;var Form1: TForm1;implementation{$R *.dfm}function ServiceStart(const ServiceName: string; const Computer: PChar = nil): Boolean;{ 启动服务}var SCM, SCH: SC_Handle; P: PChar;begin Result := False; SCM := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS); if SCM <> 0 then begin SCH := OpenService(SCM, PChar(ServiceName), SERVICE_ALL_ACCESS); if SCH <> 0 then begin Result := StartService(SCH, 0, P); CloseServiceHandle(SCH); end; CloseServiceHandle(SCM); end;end;function ServiceStop(const ServiceName: string; const Computer: PChar = nil): Boolean;{ 停止服务}var SCM, SCH: SC_Handle; ServiceStatus: TServiceStatus;begin Result := False; SCM := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS); if SCM <> 0 then begin SCH := OpenService(SCM, PChar(ServiceName), SERVICE_ALL_ACCESS); if SCH <> 0 then begin Result := ControlService(SCH, SERVICE_CONTROL_STOP, ServiceStatus); CloseServiceHandle(SCH); end; CloseServiceHandle(SCM); end;end;procedure TForm1.btnStartClick(Sender: TObject);begin ServiceStart('HZ_CommSrv');end;end.