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

7 Comments

  1. Kika says:

    Hi, in which variable should the service name be passed as a parameter?

    • Rhyous says:

      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.

  2. 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.

  3. Aakash says:

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

Leave a Reply

Powered by sweet Captcha