I've been asked many times in another article I submitted the question "can it run as a service?" The answer to that question was always "no". Using the code in this article as a starting point, the developer will be able to write their own services. This code owes a great debt of gratitude to MSDN where I originally found a tutorial. I wanted to link to that article but can no longer find it.
The developer should have a copy of Debug View so that they can see the output of the program. Debug View is part of the SysInternals suite which are a wonderful set of tools for any developer interested in probing windows applications and their interactions with the O/S,
Using the code
The compiled code produces an executable called cls.exe, which is short for command line service. The service is installed with the command cls.exe -install and uninstalled with cls.exe -uninstall. You can view the output of these operations using Debug View
There are two main classes which implement the creating, deleting, managing, starting, and stopping the service. These are CNTService and CMyService. CNTService is the base class and it is responsible for the boiler plate code that does the heavy lifting. This includes installing, uninstalling, and all the events that the service could possible receive through the services applet. CMyService is a derived class with CNTService as the base class. This is where we customize and implement the code we want our service to perform
class CMyService : public CNTService
virtual BOOL OnInit();
virtual void Run();
virtual BOOL OnUserControl(DWORD dwOpcode);
virtual void OnStop();
To add your custom behavior to the service you will simply put your code in the "Run" function. When this function returns the service stops. Since a service is normally a continuosly running process there is usually a mechanism put in place, possibly similar to this
There you have it. Now that you are armed with an easy to use template for making a Win32 C++ high performance service module you can do whatever it is you might want to do in a service.
- 11/16/2012 - Submitted article