What is Windows Service
Previously called an NT service, the core function of a Windows aervice is
to run an application in the background. There are few things that make them
different from a Windows application. A Windows service starts much before any
user logs in to the system (if it has been setup to start at boot up process).
A Windows service can also be setup in such a way that it requires a user to
start it manually – the ultimate customization!
Windows services have their own processes, and hence run very efficiently.
Normally a Windows service will not have a user interface for the simple reason
that it can be run even if no one is logged into the system, but this is not
a rule -- you can still have a Windows service with a user interface.
In windows 2000 you can view a list of services currently running on your computer
by opening Control Panel -> Administrative Tools -> Services, as shown
below:
Creating A Windows Service in VB.NET
Prior to VB.NET, creating a Windows service was a lot of work, and was left
to the C++ guru's, as you had to use some system level procedures, which were
extremely difficult. Thanks to VB.NET, however, this is becoming very easy and
we shall now learn how to create a Windows Service in VB.NET.
There are a few things that you should know before we dive in, however. Windows
services are not available under Windows 95, 98 or ME -- you need to have Windows
NT or Windows 2000 to run services.
The advantage to use .NET is that the framework incorporates all of the classes,
which shall help us to create, install and control a Windows Service. Open Visual
Studio .NET and create a new Windows service project, which we shall call "MyService".
Click OK.
Add a timer control from the toolbar in the Components tab (not the Windows Forms tab!). In the properties
window of Timer1, change the interval property to 10000, which is 10 seconds.
Examining The Source Code
Double click the timer1 control to open up the code window for Timer1_Elapsed.
Type in the following code:
Dim MyLog As New EventLog() ' create a new event log
' Check if the the Event Log Exists
If Not MyLog.SourceExists("MyService") Then
MyLog.CreateEventSource("MyService", "Myservice
Log") ' Create Log
End If
MyLog.Source = "MyService"
' Write to the Log
MyLog.WriteEntry("MyService Log", "This is log on " &
_
CStr(TimeOfDay), EventLogEntryType.Information)
Type in the following code for the OnStart procedure:
Timer1.Enabled = True
Type in the following code in the OnStop procedure:
Timer1.Enabled = False
Our application is now ready, but there are a few things that we need to do
before we move ahead when we build this application. The executable created
is not a Windows application, and hence you can't just click and run it -- it
needs to be installed as a service, but don't worry, we don't have to do it
manually -- VB.Net has a facility where we can add an installer to our program
and then use a utility to install the service.