首先
uses winsvc;//关于service的函数定义在这个unit中,d5自带的啦
要控制一个service的具体流程大概是这样的:
1、取得服务数据库的handle
2、根据服务数据库的handle取得服务的handle
3、根据服务的handle来取服务的状态或者控制服务
下面是一段取Sql server状态的程序
function tserviceform.GetSqlServerStatus: Boolean;
var
SrvHandle: SC_HANDLE;//这些都在winsvc单元中定义的
Service_Status: _SERVICE_STATUS;//在winsvc单元中有定义
SrvStatus: Integer;
begin
//取sql server的状态,如果sql server正在运行则返回true ,否则返回 false
SrvHandle := OpenSCManager('', SERVICES_ACTIVE_DATABASE, SC_MANAGER_ALL_ACCESS);
SrvHandle := OpenService(SrvHandle, PChar('MSSQLServer'), SERVICE_QUERY_STATUS or SERVICE_START);
case SrvHandle of
ERROR_ACCESS_DENIED: Memo.Lines.Add('The specified service control manager database handle does not have access to the service.');
ERROR_INVALID_HANDLE: Memo.Lines.Add('The specified handle is invalid.');
ERROR_INVALID_NAME: Memo.Lines.Add('The specified service name is invalid.');
ERROR_SERVICE_DOES_NOT_EXIST: Memo.Lines.Add('The specified service does not exist.');
end;
if QueryServiceStatus(SrvHandle, Service_Status) then
begin
//判断Sql Server服务的状态
SrvStatus := Service_Status.dwCurrentState;
case SrvStatus of
SERVICE_STOPPED: Memo.Lines.Add('The service is not running.');
SERVICE_START_PENDING: Memo.Lines.Add('The service is starting.');
SERVICE_STOP_PENDING: Memo.Lines.Add('The service is stopping.');
SERVICE_RUNNING: memo.lines.add('The service is running.');
SERVICE_CONTINUE_PENDING: Memo.Lines.Add('The service continue is pending.');
SERVICE_PAUSE_PENDING: Memo.Lines.Add('The service pause is pending.');
SERVICE_PAUSED: Memo.Lines.Add('The service is paused');
end;
Result := (SrvStatus = SERVICE_RUNNING);
end
else
Result := False;
end;
具体的service函数可以看msdn中的Service Functions部分。