/*
Description: State acquisition of Windows system Services, service paused, open, stop operation code
*/
void Cstartservicedlg::onbnclickedbutton1 ()
{
Open the Service Management object
Sc_handle HSC =:: OpenSCManager (NULL,
NULL, Generic_execute);
if (HSC = = NULL)
{
TRACE ("Open Scmanager error");
Return
}
Open the service.
Sc_handle hsvc =:: OpenService (HSC, "w3svc",
Service_start | Service_query_status | Service_stop);
if (hsvc = = NULL)
{
TRACE ("Open www erron. ");
:: Closeservicehandle (HSC);
Return
}
Get the status of a service
Service_status STATUS;
if (:: QueryServiceStatus (hsvc, &status) = = FALSE)
{
TRACE ("Get Service State error.") ");
:: Closeservicehandle (HSVC);
:: Closeservicehandle (HSC);
Return
}
Start the service if it is in a stopped state, or stop the service.
if (status.dwcurrentstate = = service_running)
{
Stop Service
if (:: ControlService (Hsvc,
Service_control_stop, &status) = = FALSE)
{
TRACE ("Stop service error.") ");
:: Closeservicehandle (HSVC);
:: Closeservicehandle (HSC);
Return
}
Wait for service to stop
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)
{
Start the service
if (:: StartService (HSVC, NULL, NULL) = = FALSE)
{
TRACE ("Start service error.") ");
:: Closeservicehandle (HSVC);
:: Closeservicehandle (HSC);
Return
}
Wait for service to start
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
}