Introduction
This article is about Windows Services in the .Net Framework. We learn how to
make and use a Windows Service in our C#.Net Framework applications.
Procedure to create a Windows Service
1. Open a new windows project in Visual Studio.
2. Right-click on the Windows Service screen and select "Add installer".
Two installers are added and displayed in the Windows Service design view.
Installers.JPG
3. Go to the service installer property and set the following properties:
- Description
- Display Name
- Service Name
- Start Type
4. Go to the service process installer property and set the account property to
"Local System".
5. Now drag a tool of evenLog1 from the tool box into the service designer and
write the following code:
public Service1()
{
InitializeComponent();
if
(!System.Diagnostics.EventLog.SourceExists("MySource"))
System.Diagnostics.EventLog.CreateEventSource("MySource",
"MyNewLog");
this.eventLog1.Source
= "MySource";
this.eventLog1.Log
= "MyNewLog";
}
On Start function
protected
override void
OnStart(string[] args)
{
this.eventLog1.WriteEntry("Windows
service start at: " +
DateTime.Now.TimeOfDay);
}
On Stop function
protected
override void
OnStop()
{
this.eventLog1.WriteEntry("Windows
service stop at: " +
DateTime.Now.TimeOfDay);
}
6. Add a setup project to install our service on the system.
7. Add project output to the setup project. Right-click on the setup project and
select "Add" -> "Project output".
8. Right-click on the setup project and select "View" -> "Custom action".
9. Right-click on the custom action that opens in the new window and add a
custom action.
10. Select an application folder and add primary output from the Windows Service
and then click "Ok".
The project output is added successfully.
11. Rebuild these two projects (Windows Service & setup) and now right-click on
setup, select "Install". The Windows Service is installed on your system
successfully.
For the first time, you need to start the service manually or you may restart
your system.
System Services Screen
You can check whether your service is working or not, just view the system event
viewer from the Control Panel (Administrative tools).
On start even log
On stop event log