How to use the service control API
We wrote a little utility a couple of years ago that stops and starts services. Which can be handy if you wish to claw back some memory. Recently we've been contacted about how this works, so below is sample code taken from the utility showing the core functionality of stopping and starting services.
#include <Winsvc.h>
// start holds if we want to start or stop the service
// this example starts the windows print spooler
bool start = true;
TCHAR szServiceName[512];
_tcscpy(szServiceName, _T("Spooler"));
// open the service control manager
SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if(hSCM==NULL)
{
//Error: could not open SCManager
return false;
}
// open the service
SC_HANDLE hService = OpenService(hSCM, szServiceName, SERVICE_ALL_ACCESS);
if(hService==NULL)
{
//Error: could not open service
return false;
}
SERVICE_STATUS ss;
memset(&ss, 0, sizeof(ss));
BOOL b = QueryServiceStatus(hService, &ss);
if(start && ss.dwCurrentState == SERVICE_STOPPED)
{
// start the service
b = StartService(hService, 0, NULL);
if(!b)
{
//Error: could not start service
return false;
}
bret = true;
}
else if(!start && ss.dwCurrentState == SERVICE_RUNNING)
{
b = ControlService(hService, SERVICE_CONTROL_STOP, &ss);
if(!b)
{
//Error: could not stop service
return false;
}
bret = true;
}
// close the service handle
CloseServiceHandle(hService);
// close the service control manager handle
CloseServiceHandle(hSCM);
If you spot any errors, or things change with new releases, please drop me an email at
admin@niris.co.uk so i can correct it.