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 <iostream>
#include <windows.h>

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;
}

4 Comments

  1. Anil says:

    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.

  2. Aakash says:

    Thanks Rhyous.. It worked exactly the way I wanted :-)

Leave a Reply