Check if there is a Service

0

Follow below:

function TfPrincipal.ServicoExiste(maquina, servico : PChar) : Boolean;
    var
      SCManHandle, Svchandle : SC_HANDLE;
      {Nome do computador onde esta localizado o serviço}
      sComputerNameEx : string;
      chrComputerName : array[0..255] of char;
      cSize           : Cardinal;
    begin
      {Verifica se nome do computador foi declarado}
      if (maquina = '') then
      begin
        {Caso não tenha sido declarado captura o nome do computador local}
        FillChar(chrComputerName, SizeOf(chrComputerName), #0);
        GetComputerName(chrComputerName, cSize);
        sComputerNameEx:=chrComputerName;
      end
      else
        sComputerNameEx := maquina;

      //ShowMessage(sComputerNameEx);

      SCManHandle := OpenSCManager(PChar(sComputerNameEx), nil, SC_MANAGER_CONNECT);

      if (SCManHandle > 0) then
      begin
        Svchandle := OpenService(SCManHandle, PChar(trim(servico)), SERVICE_QUERY_STATUS);

        //ShowMessage(Svchandle.ToString);
        if (Svchandle <> 0) then
        begin
          result := true;
          //ShowMessage('tem');
          CloseServiceHandle(Svchandle);
        end
        else
        begin
          result := false;
          //ShowMessage('n tem');
          CloseServiceHandle(SCManHandle);
        end;
      end;
    end;

Or it does not work, or I'm not able to make it work, the problem is that it does not return true even though the service name is correct and installed.

    
asked by anonymous 27.10.2015 / 17:33

1 answer

2

Well, I'm using it in separate parts, I do not like to heap everything, I found this function on the net so long ago. I believe your result is always zero in the way you are handling the parameters.

function ServiceGetStatus(sMachine, sService: PChar): DWORD;
var
  SCManHandle, SvcHandle: SC_Handle;
  SS: TServiceStatus;
  dwStat: DWORD;
begin
  dwStat := 0;
  // Open service manager handle.
  SCManHandle := OpenSCManager(sMachine, nil, SC_MANAGER_CONNECT);
  if (SCManHandle > 0) then
  begin
    SvcHandle := OpenService(SCManHandle, sService, SERVICE_QUERY_STATUS);
    // if Service installed
    if (SvcHandle > 0) then
    begin
      // SS structure holds the service status (TServiceStatus);
      if (QueryServiceStatus(SvcHandle, SS)) then
        dwStat := ss.dwCurrentState;
      CloseServiceHandle(SvcHandle);
    end;
    CloseServiceHandle(SCManHandle);
  end;
  Result := dwStat;
end;

function ServiceRunning(sMachine, sService: PChar): Boolean;
begin
  Result := SERVICE_RUNNING = ServiceGetStatus(sMachine, sService);
end;

//Aqui eu verifico se o serviço esta rodando.
procedure TForm1.Button1Click(Sender: TObject);
begin
  if ServiceRunning(nil, 'Servidor') then
    ShowMessage('Servidor esta Online!')
  else
    ShowMessage('Servidor não esta Online!')
end;
    
27.10.2015 / 18:00