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.
![NewWindowsService.JPG]()
2. Right-click on the Windows Service screen and select "Add installer".
![AddInstaller.JPG]()
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
![ServiceInstallerProperty.JPG]()
4. Go to the service process installer property and set the account property to
"Local System".
![ServiceProcessInstallerProperty.JPG]()
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.
![AddSetupProject.JPG]()
7. Add project output to the setup project. Right-click on the setup project and
select "Add" -> "Project output".
![SelectCustomAction.JPG]()
8. Right-click on the setup project and select "View" -> "Custom action".
![SelectCustomAction.JPG]()
9. Right-click on the custom action that opens in the new window and add a
custom action.
![AddCustomAction.JPG]()
10. Select an application folder and add primary output from the Windows Service
and then click "Ok".
![12.JPG]()
The project output is added successfully.
![13.JPG]()
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.
![15.JPG]()
For the first time, you need to start the service manually or you may restart
your system.
System Services Screen
![16.JPG]()
You can check whether your service is working or not, just view the system event
viewer from the Control Panel (Administrative tools).
![17.JPG]()
On start even log
![18.JPG]()
On stop event log
![19.JPG]()