求用delphi(pascal)脚本写一个用于程序安装时向系统写入一个服务的代码
求各位编程前辈用delphi(pascal)脚本写一个用于Inno Setup打包的程序安装时向系统写入一个服务的代码。要求程序安装完毕,不需要重启系统,该服务即可使用,并且在卸载时能停止并卸载该服务。服务的可执行文件路径:C:\WINDOWS\system32\HZ_CommSrv.exe,服务名称:HZ_CommSrv,显示名称:HDZB Comm Service For V2.0。我刚学习这个,找到一些零星的资料,但是编译通不过。非常感谢。
function InitializeSetup(): boolean;
begin
if IsServiceInstalled('myservice') = false then begin
if InstallService('c:\winnt\system32\myservice.exe','myservice','my service','my service is doing usefull things',SERVICE_WIN32_OWN_PROCESS,SERVICE_AUTO_START) = true then begin
StartService('myservice');
StopService('myservice');
// after stopping a service you should wait some seconds before removing
RemoveService('myservice');
// otherwise removing can fail
end
end
else if IsServiceRunning('myservice') then
MsgBox('myservice is running',mbInformation, MB_OK);
Result := false
end;
上面这些脚本是汉化新世纪论坛超级版主“老虎”发的,
我在编译时补充了IsServiceInstalled、InstallService等函数,
逻辑上也修改了一些地方,但是无法编译。
[解决办法]
编译通过的代码,非逼着我试验:
- 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.