Click here to Skip to main content
11,934,443 members (31,455 online)
Click here to Skip to main content
Add your own
alternative version


821 bookmarked

Simple Windows Service Sample

, 14 Jul 2003
Rate this:
Please Sign up or sign in to vote.
A simple application to show how to create a Windows service.


As a matter of fact Microsoft Windows services, formerly known as NT services enable you to create long-running executable applications that run in its own Windows session, which then has the ability to start automatically when the computer boots and also can be manually paused, stopped or even restarted.

This makes services ideal for use on a server or whenever you need long-running functionality that does not interfere with other users who are working on the same computer. You can also run services in the security context of a specific user account that is different from the logged-on user or the default computer account.

Windows services don’t have any interface to the user, so it can not be debugged like any regular application, but it’s debugged as a process. .NET has a very nice tool that enables processes debugging while it’s in the run status, by easily pressing Ctrl + Alt + P shortcut.


I’ve searched well so many sites about a code that I can with the help of it, build a simple Windows service, but I found a lot of code on how to manage the current Windows services of the system and that’s through the ServiceController class.

After searching the MSDN, I’ve found some nice code that helped me to create this simple Windows service. Hope it can help as a basic architecture for and usage of such a Windows service.

Using the code

At first you should simply open VS.NET and then at the File menu click on New, Project. From the New Project Dialog Box, choose the Windows service template project and name it MyNewService like shown below:

Winows Service New Project

The project template automatically adds a component class that is called Service1 by default and inherits from System.ServiceProcess.ServiceBase.

Click the designer. Then, in the Properties window, set the ServiceName property for Service1 to MyNewService.

Set the Name property to MyNewService. Set the AutoLog property to true.

In the code editor, edit the Main method to create an instance of MyNewService. When you renamed the service in step 3, the class name was not modified in the Main method. To access the Main method in VC#, expand the Component Designer generated code region.

static void Main()
    System.ServiceProcess.ServiceBase[] ServicesToRun; 
    //Change the following line to match. 
    ServicesToRun = new 
        System.ServiceProcess.ServiceBase[] { new MyNewService() }; 

In the next section, you will add a custom event log to your Windows service. Event logs are not associated in any way with Windows services. Here the EventLog component is used as an example of the type of components you could add to a Windows service.

To add custom event log functionality to your service:

  1. In the Solution Explorer, right-click Service1.vb or Service1.cs and select View Designer.
  2. From the Components tab of the Toolbox, drag an EventLog component to the designer.
  3. In the Solution Explorer, right-click Service1.vb or Service1.cs and select View Code.
  4. Edit the constructor to define a custom event log.

To access the constructor in Visual C#, expand the Component Designer generated code region.

public MyNewService()

    eventLog1.Source = "DoDyLogSourse";
    // the event log source by which 

    //the application is registered on the computer

    eventLog1.Log = "DoDyLog";

To define what happens when the service starts, in the code editor, locate the OnStart method that was automatically overridden when you created the project, and write code to determine what occurs when the service begins running:

protected override void OnStart(string[] args)
    eventLog1.WriteEntry("my service started"); 

The OnStart method must return to the operating system once the service's operation has begun. It must not loop forever or block. To set up a simple polling mechanism, you can use the System.Timers.Timer component. In the OnStart method, you would set parameters on the component, and then you would set the Timer.Enabled property to true. The timer would then raise events in your code periodically, at which time your service could do its monitoring.

To define what happens when the service is stopped, in the code editor, locate the OnStop procedure that was automatically overridden when you created the project, and write code to determine what occurs when the service is stopped:

protected override void OnStop()
    eventLog1.WriteEntry("my service stoped");

You can also override the OnPause, OnContinue, and OnShutdown methods to define further processing for your component. For the method you want to handle, override the appropriate method and define what you want to occur. The following code shows what it looks like if you override the OnContinue method:

protected override void OnContinue()
    eventLog1.WriteEntry("my service is continuing in working");

Some custom actions need to occur when installing a Windows service, which can be done by the Installer class. Visual Studio can create these installers specifically for a Windows service and add them to your project. To create the installers for your service.

  1. Return to design view for Service1.
  2. Click the background of the designer to select the service itself, rather than any of its contents.
  3. In the Properties window, click the Add Installer link in the gray area beneath the list of properties. By default, a component class containing two installers is added to your project. The component is named ProjectInstaller, and the installers it contains are the installer for your service and the installer for the service's associated process.
  4. Access design view for ProjectInstaller, and click ServiceInstaller1.
  5. In the Properties window, set the ServiceName property to MyNewService.
  6. Set the StartType property to Automatic.


To avoid being asked about the system username and password you must change the Account for the serviceProcessInstaller to LocalSystem. This is done by opening the ProjectInstaller design and then selecting the serviceProcessInstaller, press F4 and then change the Account property to LocalSystem. Or you can manually do that by creating a class that inherits from System.Configuration.Install.Installer like this:


public class ProjectInstaller : System.Configuration.Install.Installer 
private System.ServiceProcess.ServiceProcessInstaller 
private System.ServiceProcess.ServiceInstaller serviceInstaller1; 
/// <summary> 
/// Required designer variable. 
/// </summary> private System.ComponentModel.Container components = null;

public ProjectInstaller()
   // This call is required by the Designer.

   // TODO: Add any initialization after the InitComponent call 
private void InitializeComponent() 
   this.serviceProcessInstaller1 = 
     new System.ServiceProcess.ServiceProcessInstaller(); 
   this.serviceInstaller1 = 
     new System.ServiceProcess.ServiceInstaller(); 
   // serviceProcessInstaller1 
   this.serviceProcessInstaller1.Account = 
   this.serviceProcessInstaller1.Password = null;
   this.serviceProcessInstaller1.Username = null; 
   // serviceInstaller1 
   this.serviceInstaller1.ServiceName = "MyNewService"; 
   this.serviceInstaller1.StartType = 

   // ProjectInstaller 
     (new System.Configuration.Install.Installer[] 

To build your service project

  1. In Solution Explorer, right-click your project and select Properties from the shortcut menu. The project's Property Pages dialog box appears.
  2. In the left pane, select the General tab in the Common Properties folder.
  3. From the Startup object list, choose MyNewService. Click OK.
  4. Press Ctrl+Shift+B to build the project. 

Service Project Property Page

Now that the project is built, it can be deployed. A setup project will install the compiled project files and run the installers needed to run the Windows service. To create a complete setup project, you will need to add the project output, MyNewService.exe, to the setup project and then add a custom action to have MyNewService.exe installed.

To create a setup project for your service

  1. On the File menu, point to Add Project, and then choose New Project.
  2. In the Project Types pane, select the Setup and Deployment Projects folder.
  3. In the Templates pane, select Setup Project. Name the project MyServiceSetup.

A setup project is added to the solution. Next you will add the output from the Windows service project, MyNewService.exe, to the setup.

Service Setup Project

To add MyNewService.exe to the setup project

  1. In Solution Explorer, right-click MyServiceSetup, point to Add, then choose Project Output. The Add Project Output Group dialog box appears.
  2. MyNewService is selected in the Project box.
  3. From the list box, select Primary Output, and click OK.

    A project item for the primary output of MyNewService is added to the setup project. Now add a custom action to install the MyNewService.exe file.

To add a custom action to the setup project

  1. In Solution Explorer, right-click the setup project, point to View, then choose Custom Actions. The Custom Actions editor appears.
  2. In the Custom Actions editor, right-click the Custom Actions node and choose Add Custom Action. The Select Item in Project dialog box appears.
  3. Double-click the application folder in the list box to open it, select primary output from MyNewService (Active), and click OK. The primary output is added to all four nodes of the custom actions — Install, Commit, Rollback, and Uninstall.
  4. Build the setup project.

To install the Windows Service

Browse to the directory where the setup project was saved, and run the .msi file to install MyNewService.exe.

Service Setup

To start and stop your service

  1. Open the Services Control Manager by doing one of the following:
    • In Windows 2000 Professional, right-click My Computer on the desktop, then click Manage. In the Computer Management console, expand the Services and Applications node.

      - Or -

    • In Windows 2000 Server, click Start, point to Programs, click Administrative Tools, and then click Services.

      Note: In Windows NT version 4.0, you can open this dialog box from Control Panel.

  2. You should now see MyNewService listed in the Services section of the window.
  3. Select your service in the list, right-click it, and then click Start.

Right-click the service, and then click Stop.

Admin tools Services

To verify the event log output of your service

  1. Open Server Explorer and access the Event Logs node. For more information, see Working with Event Logs in Server Explorer.

    Note: The Servers node of Server Explorer is not available in the Standard Edition of Visual Basic and Visual C# .NET.

    Sample screenshot

To uninstall your service

  • On the Start menu, open Control Panel and click Add/Remove Programs, and then locate your service and click Uninstall.
  • You can also uninstall the program by right-clicking the program icon for the .msi file and selecting Uninstall.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Mahmoud Nasr
Web Developer
Saudi Arabia Saudi Arabia
i've been with .net for about 5 years since the beta 1.0 ver. along with and windows services..
am experienced in Java, C, C++, Prolog, Assembly, ASP, VB,, C# and

am very fond of Web Development and Graphics Libraries Programming like Open GL,CSGL and SDGL

worked in Microsoft Egypt Co., Delta Software and now am working in Al-Alamiah Sakhr Co., Riyadh, saudi arabia.


You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
Abed-elfattah Yacoub18-Jan-12 3:06
memberAbed-elfattah Yacoub18-Jan-12 3:06 
GeneralMy vote of 1 Pin
Martin Capodici19-Dec-11 12:10
memberMartin Capodici19-Dec-11 12:10 
Question[My vote of 1] My vote of 1 Pin
Martin Capodici19-Dec-11 12:08
memberMartin Capodici19-Dec-11 12:08 
GeneralMy vote of 5 Pin
beyondsonali5-Nov-11 1:22
memberbeyondsonali5-Nov-11 1:22 
GeneralMy vote of 5 Pin
DJ van Wyk1-Nov-11 23:13
memberDJ van Wyk1-Nov-11 23:13 
QuestionIs it just me, or was this article mostly lifted from MSDN? Pin
habeebtc31-Jul-11 11:44
memberhabeebtc31-Jul-11 11:44 
QuestionGreat article Pin
thilinasp27-Jul-11 8:06
memberthilinasp27-Jul-11 8:06 
GeneralMy vote of 5 Pin
Pascal Damman19-Jul-11 0:48
memberPascal Damman19-Jul-11 0:48 
GeneralMy vote of 4 Pin
Tawfeeq Khan18-Jul-11 12:21
memberTawfeeq Khan18-Jul-11 12:21 
GeneralMy vote of 3 Pin
Member 789450427-Jun-11 2:38
memberMember 789450427-Jun-11 2:38 
GeneralMy vote of 5 Pin
Kumar_P6-Mar-11 20:20
memberKumar_P6-Mar-11 20:20 
GeneralMy vote of 5 Pin
Marcio_Coelho10-Feb-11 7:39
memberMarcio_Coelho10-Feb-11 7:39 
GeneralMy vote of 5 Pin
suhaslive23-Dec-10 22:35
membersuhaslive23-Dec-10 22:35 
GeneralVS2005 does not exactly works the way it is described Pin
pavelgur18-Dec-10 6:47
memberpavelgur18-Dec-10 6:47 
I'm using VS2005 for followint the order described in the article. After I select Windows Service it created Service1 but it also created Program. I had this before. When I looked in the sample that I downloaded I can see just Service that comtains the logic that is in Program. I wonder how it was created. Shoud I just copy all Program code into Service?

Please let me know.

Thank you, Pavel.
Questionwin7, how??? Pin
Evs_15-Dec-10 6:30
memberEvs_15-Dec-10 6:30 
Questionhow to create windows servic Pin
Member 361471912-Nov-10 0:58
memberMember 361471912-Nov-10 0:58 
AnswerRe: how to create windows servic Pin
RaviRanjankr30-Apr-11 9:58
memberRaviRanjankr30-Apr-11 9:58 
GeneralThanks Pin
zhengxiuzhi2-Nov-10 0:13
memberzhengxiuzhi2-Nov-10 0:13 
GeneralMy vote of 5 Pin
Eric Xue (brokensnow)27-Oct-10 23:09
memberEric Xue (brokensnow)27-Oct-10 23:09 
GeneralMy vote of 5 Pin
PriyaDhana20-Oct-10 1:07
memberPriyaDhana20-Oct-10 1:07 
GeneralGreat work Pin
Heribert Bennek20-Oct-10 0:43
memberHeribert Bennek20-Oct-10 0:43 
GeneralThanks Pin
sathiyaraj s14-Oct-10 2:19
membersathiyaraj s14-Oct-10 2:19 
GeneralGreat article - how to resolve Error 1053 without resorting to Local System Account Pin
910DM21-Sep-10 6:20
member910DM21-Sep-10 6:20 
GeneralMy vote of 4 Pin
reneebea21-Sep-10 6:11
memberreneebea21-Sep-10 6:11 
GeneralMy vote of 5 Pin
Bigdeak20-Sep-10 6:40
memberBigdeak20-Sep-10 6:40 
GeneralMy vote of 4 Pin
Varun Sareen5-Sep-10 22:46
memberVarun Sareen5-Sep-10 22:46 
GeneralService in Windows Vista Pin
Waruna2-Sep-10 1:34
memberWaruna2-Sep-10 1:34 
GeneralRe: Service in Windows Vista Pin
AlainNeil30-May-11 3:00
memberAlainNeil30-May-11 3:00 
GeneralMy vote of 5 Pin
ZamsheerBasheer5-Aug-10 22:10
memberZamsheerBasheer5-Aug-10 22:10 
GeneralMy vote of 2 Pin
ansarurs15-Aug-10 21:50
memberansarurs15-Aug-10 21:50 
GeneralError: Could not connect to net.tcp://localhost:8000/. Pin
arunvtyc1-Jun-10 19:27
memberarunvtyc1-Jun-10 19:27 
QuestionWhat about interprocess communication? Pin
Maxi Ng @ TW3-May-10 17:05
memberMaxi Ng @ TW3-May-10 17:05 
GeneralMy vote of 1 Pin
Member 234263215-Apr-10 12:02
memberMember 234263215-Apr-10 12:02 
Questionhow to make it working periodically Pin
Member 448210222-Dec-09 1:35
memberMember 448210222-Dec-09 1:35 
GeneralPlease help ! Error 1001 : Must specify value for source Pin
Ramakrishnan Narayanan15-Dec-09 17:46
memberRamakrishnan Narayanan15-Dec-09 17:46 
GeneralRefering private assembly from windows application which is not present in GAC Pin
Member 426726115-Oct-09 20:31
memberMember 426726115-Oct-09 20:31 
GeneralExcellent !!!!!!!!!!! Pin
Muthuganesh8-Oct-09 21:31
memberMuthuganesh8-Oct-09 21:31 
Generalgreat article...but one gotcha! Pin
cjoki6-Oct-09 11:49
membercjoki6-Oct-09 11:49 
GeneralRe: great article...but one gotcha! Pin
Kikoz6810-Feb-10 16:08
memberKikoz6810-Feb-10 16:08 
GeneralGreat Articel, working fine in one server but not working on another server Pin
maksuda25-Aug-09 10:18
membermaksuda25-Aug-09 10:18 
GeneralRe: Great Articel, working fine in one server but not working on another server Pin
mrk982-Oct-09 3:29
membermrk982-Oct-09 3:29 
GeneralRe: Great Articel, working fine in one server but not working on another server Pin
Narendra Reddy Vajrala11-Nov-09 23:29
memberNarendra Reddy Vajrala11-Nov-09 23:29 
GeneralSystem.Security.SecurityException Pin
Karthik@DDVA18-Aug-09 12:16
memberKarthik@DDVA18-Aug-09 12:16 
GeneralError 1083: Could not start the service on Local Computer [modified] Pin
PiyushVarma2-Jul-09 16:55
memberPiyushVarma2-Jul-09 16:55 
GeneralRe: Error 1083: Could not start the service on Local Computer Pin
PiyushVarma3-Jul-09 13:43
memberPiyushVarma3-Jul-09 13:43 
GeneralRe: Error 1083: Could not start the service on Local Computer Pin
denizcaglar21-Jan-10 3:35
memberdenizcaglar21-Jan-10 3:35 
GeneralRe: Error 1083: Could not start the service on Local Computer Pin
denizcaglar21-Jan-10 5:12
memberdenizcaglar21-Jan-10 5:12 
GeneralExcellent job! Pin
Member 194465918-Jun-09 2:01
memberMember 194465918-Jun-09 2:01 
GeneralEasy Debugging Pin
reaplo28-May-09 5:26
memberreaplo28-May-09 5:26 
GeneralThanx alot!!! Pin
jasnavp20-May-09 5:30
memberjasnavp20-May-09 5:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.151126.1 | Last Updated 15 Jul 2003
Article Copyright 2003 by Mahmoud Nasr
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid