Using visual studio it is very easy to create windows service. Please follow the below steps to create a windows service.
- Open visual studio and create a new project of template "Windows Service" as shown below
- After you click OK in the above step you will see a new solution named "WindowsService1" created as shown below.
- Right click on the above screen and click "Add Installer". This will create an installer component which helps us in installing this service.
- You can notice a new component "ProjectInstaller.cs" added and opened as shown below. It has 2 controls "ServiceProcessInstaller1" and "ServiceInstaller1".
- You can set whether this service is manual, automatic, or disabled by changing the StartType property of "ServiceInstaller1" (Right click -> Properties).
- Change the "ServiceProcessInstaller1"'s property "Account" to "LocalSystem"
- Right click on Service1.cs in solution explorer and click "View Code"
- In code you will see the service event handlers "OnStart", "OnStop".
- Write code that initiates a thread in OnStart event handler.
- Write code that stops execution of the thread in OnStop event handler.
- Please see below for sample code
- Build the solution. You have the windows service built ready.
- But until we install this service we cannot see it is running or not.
- To install this service you need to open the Visual Studio 2005/2008 Command prompt in Start->Visual Studio 2005/2008->Visual Studio Tools
- Run the command : InstallUtil.exe Windows_Service_EXE_Full_Path
- Here Windows_Service_EXE_Full_Path is the exe generated for the WindowsService1 project. Let's say the full path of the exe is C:/WindowsService1/Bin/Debug/WindowsService1.exe then our command to install it would be like this.
- InstallUtil.exe C:/WindowsService1/Bin/Debug/WindowsService1.exe
- If the above command is successful then you will notice a new service named "Service1" is shown in Control Panel->Administrative Tools/Services
- To uninstall a service, InstallUtil.exe -u C:/WindowsService1/Bin/Debug/WindowsService1.exe
- To make the life easier to install/uninstall windows services we can create a setup project which will let people easily install/uninstall with a wizard Please read this link. http://cherupally.blogspot.com/2009/09/how-to-create-setup-project-to-install.html
3 comments:
Your artikel is helpfull. But I'm not familiar with C#. I try it in vb.
In vb service class is so simple, there is no inherits class and sub New().
Is it ok to apply you code directly on OnStart method?
Yes. Putting my code in OnStart method works in VB also. Please try it and let me know f there are any issues.
This article is very nice with step wise. It would be great if you would also add steps for how to debug the Service.
Post a Comment