標籤:windows 服務
/*
介紹:對Windows系統服務的狀態擷取,服務暫停,開啟,停止作業碼
*/
void CStartServiceDlg::OnBnClickedButton1()
{
// 開啟服務管理對象
SC_HANDLE hSC = ::OpenSCManager( NULL,
NULL, GENERIC_EXECUTE);
if( hSC == NULL)
{
TRACE( "open SCManager error");
return;
}
// 開啟服務。
SC_HANDLE hSvc = ::OpenService( hSC, "W3SVC",
SERVICE_START | SERVICE_QUERY_STATUS | SERVICE_STOP);
if( hSvc == NULL)
{
TRACE( "Open www erron。");
::CloseServiceHandle( hSC);
return;
}
// 獲得服務的狀態
SERVICE_STATUS status;
if( ::QueryServiceStatus( hSvc, &status) == FALSE)
{
TRACE( "Get Service state error。");
::CloseServiceHandle( hSvc);
::CloseServiceHandle( hSC);
return;
}
//如果處於停止狀態則啟動服務,否則停止服務。
if( status.dwCurrentState == SERVICE_RUNNING)
{
// 停止服務
if( ::ControlService( hSvc,
SERVICE_CONTROL_STOP, &status) == FALSE)
{
TRACE( "stop service error。");
::CloseServiceHandle( hSvc);
::CloseServiceHandle( hSC);
return;
}
// 等待服務停止
while( ::QueryServiceStatus( hSvc, &status) == TRUE)
{
::Sleep( status.dwWaitHint);
if( status.dwCurrentState == SERVICE_STOPPED)
{
AfxMessageBox( "stop success。");
::CloseServiceHandle( hSvc);
::CloseServiceHandle( hSC);
return;
}
}
}
else if( status.dwCurrentState == SERVICE_STOPPED)
{
// 啟動服務
if( ::StartService( hSvc, NULL, NULL) == FALSE)
{
TRACE( "start service error。");
::CloseServiceHandle( hSvc);
::CloseServiceHandle( hSC);
return;
}
// 等待服務啟動
while( ::QueryServiceStatus( hSvc, &status) == TRUE)
{
::Sleep( status.dwWaitHint);
if( status.dwCurrentState == SERVICE_RUNNING)
{
AfxMessageBox( "start success。");
::CloseServiceHandle( hSvc);
::CloseServiceHandle( hSC);
return;
}
}
}
TRACE( "start error。");
::CloseServiceHandle( hSvc);
::CloseServiceHandle( hSC);
return;
}