#include <windows.h>
#include <winsvc.h>
#include <stdio.h>


void control_service()
{
 // 打开服务管理对象
 SC_HANDLE hSC = OpenSCManager( NULL, 
 NULL, GENERIC_EXECUTE);
 if( hSC == NULL)
 {
printf("OpenScManager error:%d\n",GetLastError());
 return;
 }
 // 打开打印服务。
 SC_HANDLE hSvc = OpenService( hSC, "Spooler",
 SERVICE_START | SERVICE_QUERY_STATUS | SERVICE_STOP);
 if( hSvc == NULL)
 {
printf("OpenService error:%d\n",GetLastError());
CloseServiceHandle( hSC);
return;
 }
 // 获得服务的状态
 SERVICE_STATUS status;
 if( QueryServiceStatus( hSvc, &status) == FALSE)
 {
printf("QueryServiceStatus error:%d\n",GetLastError());
CloseServiceHandle( hSvc);
CloseServiceHandle( hSC);
return;
 }
 //如果处于停止状态则启动服务,否则停止服务。
 if( status.dwCurrentState == SERVICE_RUNNING)
 {
// 停止服务
if( ControlService( hSvc, 
SERVICE_CONTROL_STOP, &status) == FALSE)
{
printf("ControlService Stop error:%d\n",GetLastError());
CloseServiceHandle( hSvc);
CloseServiceHandle( hSC);
return;
}
// 等待服务停止
while( QueryServiceStatus( hSvc, &status) == TRUE)
{
Sleep( status.dwWaitHint);
if( status.dwCurrentState == SERVICE_STOPPED)
{
printf("QueryServiceStatus stop success.\n");
CloseServiceHandle( hSvc);
CloseServiceHandle( hSC);
return;
}
}
 }else if( status.dwCurrentState == SERVICE_STOPPED){
// 启动服务
if( StartService( hSvc, NULL, NULL) == FALSE)
{
printf("start service error:%d\n",GetLastError());
CloseServiceHandle( hSvc);
CloseServiceHandle( hSC);
return;
}
// 等待服务启动
while( QueryServiceStatus( hSvc, &status) == TRUE)
{
Sleep( status.dwWaitHint);
if( status.dwCurrentState == SERVICE_RUNNING)
{
printf("start success.\n");
CloseServiceHandle( hSvc);
CloseServiceHandle( hSC);
return;
}
}
 }
printf("Start error:%d\n",GetLastError());
CloseServiceHandle( hSvc);
CloseServiceHandle( hSC);
return;
}


int main()
{
control_service();
while(1){
Sleep(1000);
}
return 0;
}
09-06 01:26