檢測(cè)指定名稱的服務(wù)運(yùn)行狀態(tài),若服務(wù)暫停則恢復(fù)服務(wù),若服務(wù)停止則啟動(dòng)服務(wù)。 BOOL DetectService(
char* ServiceName)
{
SC_HANDLE hSC = ::OpenSCManager( NULL, NULL, GENERIC_EXECUTE);
if( hSC == NULL)
{
return false;
}
// 打開(kāi)服務(wù)
SC_HANDLE hSvc = ::OpenService( hSC, ServiceName,
SERVICE_START | SERVICE_QUERY_STATUS | SERVICE_STOP);
if( hSvc == NULL)
{
return false;
::CloseServiceHandle( hSC);
}
// 獲得服務(wù)的狀態(tài)
SERVICE_STATUS status;
if( ::QueryServiceStatus( hSvc, &status) == FALSE)
{
return false;
::CloseServiceHandle( hSvc);
::CloseServiceHandle( hSC);
}
ofstream outfile;
outfile.open(".\\檢測(cè)結(jié)果.txt",ios::app);
//服務(wù)已啟動(dòng)
if( status.dwCurrentState == SERVICE_RUNNING)
{
outfile<<"服務(wù)";
outfile<<ServiceName;
outfile<<"已啟動(dòng) \n";
return true;
}
//如果處于停止?fàn)顟B(tài)則啟動(dòng)服務(wù)
if( status.dwCurrentState == SERVICE_STOPPED)
{
outfile<<"服務(wù)";
outfile<<ServiceName;
outfile<<"處于停止?fàn)顟B(tài) \n";
// 啟動(dòng)服務(wù)
if( ::StartService( hSvc, NULL, NULL) == FALSE)
{
return false;
::CloseServiceHandle( hSvc);
::CloseServiceHandle( hSC);
}
// 等待服務(wù)啟動(dòng)
while( ::QueryServiceStatus( hSvc, &status) == TRUE)
{
// ::Sleep( status.dwWaitHint);
if( status.dwCurrentState == SERVICE_RUNNING)
{
::CloseServiceHandle( hSvc);
::CloseServiceHandle( hSC);
outfile<<"啟動(dòng)成功 \n";
return true;
}
}
}
//如果處于暫停狀態(tài),則恢復(fù)
if( status.dwCurrentState == SERVICE_PAUSED)
{
outfile<<"服務(wù)";
outfile<<ServiceName;
outfile<<"處于停止?fàn)顟B(tài) \n";
CString str;
str.Format("net continue %s",ServiceName);
WinExec(str,SW_SHOW);
while( ::QueryServiceStatus( hSvc, &status) == TRUE)
{
if( status.dwCurrentState == SERVICE_RUNNING)
{
::CloseServiceHandle( hSvc);
::CloseServiceHandle( hSC);
outfile<<"恢復(fù)服務(wù)成功 \n";
return true;
}
}
}
outfile<<"\n";
outfile.close();
::CloseServiceHandle( hSvc);
::CloseServiceHandle( hSC);
return false;
}
http://blog.csdn.net/suiyuan1767/article/details/6712516