Las siguientes funciones sirven para saber si un servicio esta iniciado. Pueden resultarnos útiles, por ejemplo, si nuestra aplicación se inicia al arrancar el equipo y necesitamos esperar a que el servicio de la base de datos este iniciado.
Código Delphi
[-]
uses WinSvc;
function isRunning(Nombre: String): Boolean;
var
ServiceControlManager: SC_HANDLE;
Service: SC_HANDLE;
ServiceStatus: SERVICE_STATUS;
begin
Result:= FALSE;
ServiceControlManager:= OpenSCManager(nil, nil, SC_MANAGER_CONNECT);
if ServiceControlManager <> 0 then
begin
Service:= OpenService(ServiceControlManager,PChar(Nombre),GENERIC_READ);
if Service <> 0 then
begin
if QueryServiceStatus(Service, ServiceStatus) then
Result:= ServiceStatus.dwCurrentState = SERVICE_RUNNING;
CloseServiceHandle(Service);
end;
CloseServiceHandle(ServiceControlManager);
end;
end;
function Esperar(Nombre: String; TimeOut: Cardinal): Boolean;
var
Ticks: Cardinal;
begin
Result:= TRUE;
Ticks:= GetTickCount;
while not isRunning(Nombre) do
begin
Sleep(10);
if GetTickCount - Ticks > TimeOut then
begin
Result:= FALSE;
Exit;
end;
end;
end;
La primera función nos dice si un servicio esta iniciado, y la segunda espera hasta que el servicio se inicia o se cumple el tiempo de espera. Si el servicio no esta iniciado cuando se cumple el tiempo de espera la función devuelve FALSE. Un ejemplo de como usar lo anterior:
Código Delphi
[-]
if Esperar('NombreDelServicio',15000) then
begin
end else
begin
end;