这可是我研究了很久的一个主打函数,送给各位了:
// W3SVC ---Web Service MSSQLSERVER --- MS SQL Service OverTime 为超时处理,单位秒
Function CtrlService(ServiceName: string;
Status: Boolean;
OverTime:Integer): Boolean;
//控制WINDOWS的服务启动与停止
var
lpServiceArgVectors: Pchar;
hscmanager, hService: SC_HANDLE;
returnstatus: TServiceStatus;
i:Integer;
begin
Result := True;
lpServiceArgVectors := nil;
hscmanager := OpenSCManager(nil, nil, SC_MANAGER_ENUMERATE_SERVICE);
// 打开service control manager database
if hscmanager = 0 then
begin
Result := False;
exit;
end;
hService := OpenService(hscmanager, Pchar(ServiceName), SERVICE_ALL_ACCESS);
//打开W3SVC服务
if hService = 0 then
begin
CloseServiceHandle(hscmanager);
CloseServiceHandle(hService);
Result := False;
exit;
end;
if not QueryServiceStatus(hService, returnstatus) then
begin
CloseServiceHandle(hscmanager);
CloseServiceHandle(hService);
Result := False;
exit;
end;
//查看该Service的状态
i:=0;
if Status then
//如果是启动服务
begin
if (returnstatus.dwCurrentState = SERVICE_STOPPED) and (not StartService(hService, 0, lpServiceArgVectors)) then
Result := False
else
while (i<OverTime) and (returnstatus.dwCurrentState <> SERVICE_RUNNING) do
begin
Sleep(1000);
QueryServiceStatus(hService, returnstatus);
Application.ProcessMessages;
inc(i);
end;
CloseServiceHandle(hscmanager);
CloseServiceHandle(hService);
exit;
end
else
//如果是停止服务
begin
if (returnstatus.dwCurrentState = SERVICE_RUNNING) and (not ControlService(hService, SERVICE_CONTROL_STOP, returnstatus)) then
Result := False
else
while (i<OverTime) and (returnstatus.dwCurrentState <> SERVICE_STOPPED) do
begin
Sleep(1000);
QueryServiceStatus(hService, returnstatus);
Application.ProcessMessages;
inc(i);
end;
CloseServiceHandle(hscmanager);
CloseServiceHandle(hService);
exit;
end;
end;