VB.NET - Creating a Windows Service Part I This article shows us how to start, install, create and stop a service with VB.Net. In order to write application that constantly monitors some files, creates a log file, or anything else which runs constantly in the background while the machine is busy doing something else, the best way to this used to be to run a windows application continuously or at a regular interval with the use of Windows scheduler. One disadvantage to this is that someone has to log into the system to start the application. Windows Service
The main function of a Windows service 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. A Windows service can also be setup in such a way that it requires a user to start it labor-intensively.
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. Windows services have their own processes, and hence run very efficiently.
VB.NET and Windows Service Creating a Windows service in VB.NET was difficult but it is becoming easy to create a Windows Service in VB.Net. Few things you should know before we go into it. You need to have Windows NT or Windows 2000 to run services because Windows services are not available under Windows 95, 98 or ME. The framework incorporates all of the classes, which shall help us to create, install and control a Windows Service. And this is the advantage to use .NET. Open Visual Studio .NET and create a new Windows service project, named "My Service". Add a timer control from the toolbar in the Components tab. In the properties window of Timer1, change the interval property to 10000, which is 10 seconds.
The Source 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)
The On tart procedure:
Timer1.Enabled = True
Type in the following code in the OnStop procedure:
Timer1.Enabled = False
Conclusion
Now the function is ready, but there are a few things that we should notice here. 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. |