包含頭文件:#include <winsvc.h>
以下以web服務為例:
#include <winsvc.h>
void CStartServiceDlg::OnBnClickedButton1()
{
// 打開服務管理對象
SC_HANDLE hSC = ::OpenSCManager( NULL,
NULL, GENERIC_EXECUTE);
if( hSC == NULL)
{
TRACE( "open SCManager error");
return;
}
// 打開www服務。
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;
}