Using a Service Under Windows

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.


This article was contributed by Elmue.

Environment: Windows NT/2000/XP

Description

This demo shows how to create, start, stop, and delete a service under Windows NT/2000/XP.

This program demonstrates the use of these API commands:

  • OpenSCManager()
  • CloseServiceHandle()
  • CreateService()
  • OpenService()
  • SetServiceStatus()
  • DeleteService()
  • RegisterServiceCtrlHandler()
  • StartServiceCtrlDispatcher()
  • LPSERVICE_MAIN_FUNCTION
  • LPHANDLER_FUNCTION

Try this demo with an Administrator Account and a normal User or Guest Account! This program logs all commands it receives and executes into the logfile C:\DemoService.txt.

This program is used in two modes:

  • Service.exe (without parameters) runs the program with the GUI (see screenshot)
  • Service.exe /Service runs it as a Service (Windows calls Service.exe with the “/Service” parameter if the already installed Service is started)

In a Service, it is not possible to set a normal Timer (SetTimer()) because the service does not own a window and can’t receive Window Messages.

For demonstration, I set a waitable timer that writes every five seconds to the log file, even when no user is logged on.

Downloads

Download demo project – 10 Kb

Download source – 15 Kb

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read