bool CloseWindowsService(TCHAR* service) //服务名
{
SC_HANDLE hSC = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hSC == NULL)
{
printf("OpenSCManager fail(%ld)", GetLastError());
return false;
}
// open service
SC_HANDLE hSvc = ::OpenService(hSC, service,
SERVICE_START | SERVICE_QUERY_STATUS | SERVICE_STOP);
if (hSvc == NULL)
{
::CloseServiceHandle(hSC);
return false;
}
// get service status
SERVICE_STATUS status;
if (::QueryServiceStatus(hSvc, &status) == FALSE)
{
::CloseServiceHandle(hSvc);
::CloseServiceHandle(hSC);
return false;
}
//if status == running, stop the service
if (status.dwCurrentState == SERVICE_RUNNING)
{
if (::ControlService(hSvc,
SERVICE_CONTROL_STOP, &status) == FALSE)
{
::CloseServiceHandle(hSvc);
::CloseServiceHandle(hSC);
return false;
}
//wait the stop operation
while (::QueryServiceStatus(hSvc, &status) == TRUE)
{
::Sleep(status.dwWaitHint);
if (status.dwCurrentState == SERVICE_STOPPED)
{
::CloseServiceHandle(hSvc);
::CloseServiceHandle(hSC);
return true;
}
}
}
::CloseServiceHandle(hSvc);
::CloseServiceHandle(hSC);
return true;
}