// 停止指定机器上的指定服务
// strMachine: 机器名,如指定本机,则留空
// strService: 服务名.
bool MyStopService(String strMachine, String strService)
{
// service control manager handle and service handle
SC_HANDLE schm, schs;
// service status
SERVICE_STATUS SrvStatus;
// check point
DWORD dwChkPoint;
// connect to the service control manager
schm = OpenSCManager(strMachine.c_str(), NULL, SC_MANAGER_CONNECT);
if(schm > 0)
{
// open a handle to the specified service
// we want to stop the service and query service status
schs = OpenService(schm, strService.c_str(), SERVICE_STOP | SERVICE_QUERY_STATUS);
if(schs > 0)
{
if(ControlService(schs, SERVICE_CONTROL_STOP, &SrvStatus))
{
// check status
if(QueryServiceStatus(schs, &SrvStatus))
{
while(SERVICE_STOPPED != SrvStatus.dwCurrentState)
{
// dwCheckPoint contains a value that the service
// increments periodically to report its progress
// during a lengthy operation.
// save current value
dwChkPoint = SrvStatus.dwCheckPoint;
// wait a bit before checking status again
// dwWaitHint is the estimated amount of time
// the calling program should wait before calling
// QueryServiceStatus() again
// idle events should be handled here...
Sleep(SrvStatus.dwWaitHint);
if(!QueryServiceStatus(schs, &SrvStatus))
// couldn't check status break from the loop
break;
if(SrvStatus.dwCheckPoint < dwChkPoint)
// QueryServiceStatus didn't increment
// dwCheckPoint as it should have.
// avoid an infinite loop by breaking
break;
}
}
}
} // end of if(schs > 0)
// close service handle
CloseServiceHandle(schs);
}
// close service control manager handle
CloseServiceHandle(schm);
// return TRUE if the service status is stopped
return (SERVICE_STOPPED == SrvStatus.dwCurrentState);
}
//---------------------------------------------------------------------------
// 调用举例: 停止本机的信使服务.
// 在停止服务时需要等待一段时间,可以自己添加一个类似Win2k中的停止服务时的进度条.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
if(MyStopService("", "Messenger"))a
ShowMessage("搞定!");
}
//---------------------------------------------------------------------------