A simple example of starting and stopping a service in windows using C++
Hey all,
Here is a simple example of starting and stopping a service in C++. Just pass the service name as a parameter and the service will switch states. If stopped, it will start. If started, it will stop.
// StartStopService.cpp : Defines the entry point for the console application.
//
#include “stdafx.h”
#include
#include
int _tmain(int argc, _TCHAR* argv[])
{
SC_HANDLE serviceDbHandle = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
SC_HANDLE serviceHandle = OpenService(serviceDbHandle, argv[1], SC_MANAGER_ALL_ACCESS);
SERVICE_STATUS_PROCESS status;
DWORD bytesNeeded;
QueryServiceStatusEx(serviceHandle, SC_STATUS_PROCESS_INFO,(LPBYTE) &status,sizeof(SERVICE_STATUS_PROCESS), &bytesNeeded);
if (status.dwCurrentState == SERVICE_RUNNING)
{// Stop it
BOOL b = ControlService(serviceHandle, SERVICE_CONTROL_STOP, (LPSERVICE_STATUS) &status);
if (b)
{
std::cout << "Service stopped." << std::endl;
}
else
{
std::cout << "Service failed to stop." << std::endl;
}
}
else
{// Start it
BOOL b = StartService(serviceHandle, NULL, NULL);
if (b)
{
std::cout << "Service started." << std::endl;
}
else
{
std::cout << "Service failed to start." << std::endl;
}
}
CloseServiceHandle(serviceHandle);
CloseServiceHandle(serviceDbHandle);
return 0;
}
[/sourcecode]
Very nice. Elegant and easy to follow. Thanks for sharing!
Thanks!!
Hi, in which variable should the service name be passed as a parameter?
Actually in this example, the service name is passed as the first parameter to the compiled exe.
If you are just trying to reuse the code, you can see that the service name is passed in as argv[1] to the OpenService method in line 11.
Thanks, Its working but how can i give service names if they have space between them like "My Service". this type of services are not responding.
I just use quotes and it worked.
I had this service and it worked perfectly with quotes: "HP Health Check Service"
Thanks Rhyous.. It worked exactly the way I wanted 🙂
Glad the post helped you. I try to post anything I learn so it is easier for the next guy.