A Windows Service without a template
Written by Harry Fairhead   
Friday, 14 August 2009
Article Index
A Windows Service without a template
A simple service
Using Timers
Event log service
Other logs


Most of the time we want to write an application that the user opens and interacts with in complicated ways; occasionally we want to do almost exactly the opposite!

A Windows service is a program with a minimal user interface that can be set to automatically start when a machine is turned on, even before any user logs on.

There are lots of standard services that provide facilities such as networking that are at the very heart of the Windows operating system, but it’s fairly easy to create your own.

Why would you want to?

The simple answer is that whenever you want an application to run independently of which user is logged on, and to provide a facility that should be available from the moment a machine is powered on, then you should write a service.

As an example, we are going to implement a simple service that reads the machine’s event log and sends an email if it finds any error messages. This also provides an opportunity to find out how the .NET framework not only makes services easy but how it makes event logging trivial too.

A simple service

The simplest way to create a service is to use Visual Studio’s service template.

Unfortunately this isn’t included in the Express or Standard editions and so many programmers wrongly conclude that they can’t use these to create a service.

Creating a service without the help of the template is fairly easy - so much so that it’s a mystery why Microsoft felt the need to reserve it for the more expensive editions of Visual Studio.

There are two key ideas in the creation of a service.

The first is that there is a supplied ServiceBase class which provides all the methods and properties needed to implement a service. What this means is that creating your service is just a matter of deriving a new class from ServiceBase and then customising and adding to it to make it do exactly what you want.

The second idea is the use of a supplied installation class along with the .NET tool InstallUtil. You can find InstallUtil in the Windows\Microsoft.NET\Framework\Vx.y.zzzzz directory where the x, y and z refer to the latest version of the framework. When you type the command:

InstallUtil MyProg.exe

IntallUtil looks for any classes within MyProg.exe that carry the


attribute and if it finds any it runs the class constructor for that class.

This is a fairly general mechanism for installing applications but we are going to use it specifically to install our service.



Last Updated ( Friday, 14 August 2009 )