Creating A Windows Service

 


Intro

Window Services are applications that run in the background to execute some particular task. They are started by Windows when it first boots.

These are my notes on Tutorial: Create a Windows service app


Documentation

 


Tips and Tidbits

  • The Windows Service Control Manager (SCM) runs your service via its Main method in Program.cs.

  • SCM expects to get control quickly after invoking the service’s Main. If not, it will assume the service failed to start.

  • Windows services don’t allow “pop ups” or any other type of user dialog to appear. They must run stand-alone/

 


Creating The Visual Studio Project

 

 

  • Rename the default service class to your desired class name (in my example MyFirstWindowService)

 

  • Select the properties icon (wrench) for your class and then click on the designer tab (MyFirstWindowService.cs [Design]). Note that the properties window now changes.

  • Change the defaut service name (Service1) there to your own (MyFirstWindowService). This the service name that Windows will use in its management of the service and there can only be one such named service.

 

  • After you make the above change, you will note that the Designer automatically changes the code to include the new name

 

 


Other properties you can configure

  • Set AutoLog to TRUE (default) so Windows can automatically log certain events for you.

 


Service Entry Point

The Visual Studio template will generate a Program class with a Main method that will be entry point into your service.

ServicesToRun is an array of services that will be kicked off, each on its own thread. You can add more services in this array if need to.

 

 


Add custom event log functionality

Let’s add event logs to the service.

Open the Designer’s toolbox

 

If the EventLog component is not available in your toolbox, right click on the Components entry and Choose Toolbox items

 

 

  • Drag and Drop The EventLog component to your service class Designer window.

  • View the source code for the class and manually enter the EventLog initialization code below

 

public MyFirstWindowsService() { InitializeComponent(); eventLog = new EventLog(); if (!EventLog.SourceExists("MySource")) { EventLog.CreateEventSource("MySource", "MyNewLog"); } eventLog.Source = "MySource"; eventLog.Log = "MyNewLog"; }

Add installers to the service


Before you can run a Windows Service, you need to install the Installer, which registers it with the Service Control Manager.

  • Studio adds a component class named ProjectInstaller, which contains two installers, to your project. These installers are for your service and for the service's associated process.

 

 

  • Use the Description property to describe the purpose of the installed service to the user. The user can view the service description in applications that display details for installed services.

 

 

© Roger Cruz - All rights reserved