Simple service base class for Windows






2.09/5 (7 votes)
Mar 24, 2004

83156

1798
This class provides a simple way to implement Windows service in C++.
Introduction
The purpose of this code is to show how to make a simple C++ class which wraps WinNT API for service programs. With this class, you can implement a Windows service in a few minutes. This class is not made for advanced service programming, but it should not be too hard modify this source to append any additional functionality. When I implemented this class, I was trying to copy the interface of ServiceBase
class from .NET framework. I think it's good design for most requirements of service applications.
Have on mind that using this class you can't implement multiple services in one application. I will implement this in future updates and add more functionality.
Using the code
I didn't provide a sample project this time but here is the code you need for that:
#include <windows.h> #include <stdio.h> #include "smart_reference.h" #include "I_ServiceBase.h" void WriteLog(const char* message) { FILE* pFile = fopen("C:\\test_service.log","a"); if(pFile) { fwrite(message, sizeof(char), strlen(message), pFile); fclose(pFile); } } class TestService : public CI_ServiceBase { public: TestService() { m_bStop = false; } ~TestService() { CI_ServiceBase::~CI_ServiceBase(); } virtual void OnStart(int argc, LPTSTR* argv) { WriteLog("Server started.\n\r"); while(!m_bStop) { Sleep(1000); } } virtual void OnStop() { WriteLog("Server stopped.\n\r"); m_bStop = true; } virtual void OnPause() { WriteLog("Server paused.\n\r"); } virtual void OnContinue() { WriteLog("Server continued.\n\r"); } private: bool m_bStop; }; TestService ts; int main(int argc, char* argv[]) { ts.set_CanPauseAndContinue(false); ts.set_ServiceName("isw_test"); CI_ServiceBase::Run((TestService*)ts); return 0; }