Delphi 服务程序[3] 安装、卸载 的方法

Delphi 服务程序[3] 安装、卸载 的方法

1、CMD命令窗口bat安装(假设生成SerTest.exe)

SerTest.exe /install   //安装
SerTest.exe /unstall   //卸载

可以在命令行后面加/silent参数,使其不弹出安装、卸载成功的提示框,例如

SerTest.exe /install /silent

2、通过sc命令来创建、删除服务

sc create "ServiceName" binpath= "C:UsersAdministratorDesktopSerTest.exe"
sc delete ServiceName

3、Delphi 代码 安装、卸载、开启、停止、检查

unit SerMgr;

interface
  uses Windows,Messages,SysUtils,Winsvc,Dialogs;

  function CreateServices(Const SvrName,FilePath:String):Boolean;
  function DeleteServices(Const SvrName: String):Boolean;

implementation

{建立服务}
function  CreateServices(Const SvrName,FilePath: String): Boolean;
var
  sMgr, sHandle:SC_HANDLE;
begin
  Result:=False;
  if FilePath = '' then Exit;

  sMgr := OpenSCManager(nil,nil,SC_MANAGER_CREATE_SERVICE);

  if sMgr <= 0 then Exit;
  try
    sHandle := CreateService(sMgr, PChar(SvrName),
    PChar(SvrName),
    SERVICE_ALL_ACCESS,
    SERVICE_INTERACTIVE_PROCESS or SERVICE_WIN32_OWN_PROCESS,
    SERVICE_AUTO_START,SERVICE_ERROR_NORMAL,
    PChar(FilePath),nil,nil,nil,nil,nil);
    if sHandle <= 0 then begin
      ShowMessage( SysErrorMessage(GetlastError));
      Exit;
    end;
    CloseServiceHandle(sMgr);
    CloseServiceHandle(sHandle);

    Result := True;
  except
    CloseServiceHandle(sMgr);
    CloseServiceHandle(sHandle);
    Exit;
  end;
end;

{卸载服务}
function DeleteServices(Const SvrName: String): Boolean;
var
  sMgr, sHandle:SC_HANDLE;
begin
  Result:=False;
  sMgr := OpenSCManager(nil,nil,SC_MANAGER_ALL_ACCESS);
  if sMgr <= 0 then  Exit;
  sHandle :=OpenService(sMgr,PChar(SvrName),STANDARD_RIGHTS_REQUIRED);
  if sHandle <= 0 then Exit;
  try
    Result := DeleteService(sHandle);

    if not Result then
      ShowMessage(SysErrorMessage(GetlastError));
    CloseServiceHandle(sHandle);
    CloseServiceHandle(sMgr);
  except
    CloseServiceHandle(sHandle);
    CloseServiceHandle(sMgr);
    Exit;
  end;
end;


end.

  

  

创建时间:2021.01.21  更新时间: 

 

posted on 2021-01-21 09:08  滔Roy  阅读(673)  评论(0编辑  收藏  举报

导航