Sometimes you need to know the Process Id (PID) of a running service. Since Windows 2003 you can use the tasklist.exe tool with the /SVC switch. But how to do this programmatically?

The QueryServiceStatusEx API returns a SERVICE_STATUS_PROCESS structure that contains the PID.

The code is not very complicated:

text Download
uses JwaWinSvc;

function GetServicePid(const Servicename: String): DWORD;
var
  hScm: THandle;
  hSvc: THandle;
  ssp: SERVICE_STATUS_PROCESS;
  dwSize: DWORD;
begin
  hScm := OpenSCManager(nil, nil, SC_MANAGER_CONNECT);
  if hScm = 0 then
    Exit(0);

  try
    hSvc := OpenService(hScm, PChar(Servicename), SERVICE_QUERY_STATUS);
    if hSvc = 0 then
      Exit(0);

    try
      if not QueryServiceStatusEx(hSvc, SC_STATUS_PROCESS_INFO, @ssp,
        SizeOf(ssp), dwSize) then
        Exit(0);

      Result := ssp.dwProcessId;

    finally
      CloseServiceHandle(hSvc);
    end;
  finally
    CloseServiceHandle(hScm);
  end;
end;