Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2010
Visual Studio
 Walkthrough: Creating a Windows Ser...
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2010/.NET Framework 4

Other versions are also available for the following:
Visual Studio 2010
Walkthrough: Creating a Windows Service Application in the Component Designer

Updated: July 2011

NoteNote

The Windows Service template and associated functionality is not available in the Standard Edition of Visual Studio.

The procedures in this topic demonstrate creating a simple Windows Service application that writes messages to an event log. The basic steps that you perform to create and use your service include the following:

  • Create a project by using the Windows Service application template. This template creates a class for you that inherits from ServiceBase and writes much of the basic service code, such as the code to start the service.

  • Write the code for the OnStart and OnStop procedures, and override any other methods that you want to redefine.

  • Add the necessary installers for your service application. By default, a class that contains two or more installers is added to your application when you click the Add Installer link: one to install the process, and one for each associated service that your project contains.

  • Build your project.

  • Create a setup project to install your service, and then install it.

  • Access the Windows Services Control Manager and start your service.

To begin, you create the project and set values that are required for the service to function correctly.

NoteNote

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

To create and configure your service

  1. On the File menu, click New Project.

    The New Project dialog box opens.

  2. Select Windows Service in the list of Visual Basic or Visual C# project templates, and name the project MyNewService. Click OK.

    NoteNote

    The project template automatically adds a component class named Service1 that inherits from System.ServiceProcess..::.ServiceBase.

  3. Click the designer to select Service1. Then, in the Properties window, set the ServiceName and the (Name) property for Service1 to MyNewService.

In the next section, you add a custom event log to the 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 component you could add to a Windows service.

To add custom event log functionality to your service

  1. In 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 Solution Explorer, right-click Service1.vb or Service1.cs and select View Code.

  4. Add or edit the constructor to define a custom event log.

    Visual Basic
    ' To access the constructor in Visual Basic, select New from the
    ' method name drop-down list. 
    Public Sub New()
      MyBase.New()
      InitializeComponent()
      If Not System.Diagnostics.EventLog.SourceExists("MySource") Then
          System.Diagnostics.EventLog.CreateEventSource("MySource",
          "MyNewLog")
      End If
      EventLog1.Source = "MySource"
      EventLog1.Log = "MyNewLog"
    End Sub
    
    C#
        public MyNewService()
        {
            InitializeComponent();
            if (!System.Diagnostics.EventLog.SourceExists("MySource")) 
            {         
                    System.Diagnostics.EventLog.CreateEventSource(
                        "MySource","MyNewLog");
            }
            eventLog1.Source = "MySource";
            eventLog1.Log = "MyNewLog";
        }
    

To define what occurs 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 starts running:

    Visual Basic
    ' To access the OnStart in Visual Basic, select OnStart from the
    ' method name drop-down list. 
    Protected Overrides Sub OnStart(ByVal args() As String)
      EventLog1.WriteEntry("In OnStart")
    End Sub
    
    C#
        protected override void OnStart(string[] args)
        {
            eventLog1.WriteEntry("In OnStart");
        }
    
    NoteNote

    A service application is designed to be long running. Therefore, it usually polls or monitors something in the system. The monitoring is set up in the OnStart method. However, OnStart does not actually do the monitoring. The OnStart method must return to the operating system after 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 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 occurs when the service is stopped

  • In the Code Editor, select the OnStop procedure from the Method Name drop-down list, which was automatically overridden when you created the project. Write code to determine what occurs when the service is stopped:

    Visual Basic
    Protected Overrides Sub OnStop()
      EventLog1.WriteEntry("In OnStop.")
    End Sub
    
    C#
        protected override void OnStop()
        {
            eventLog1.WriteEntry("In onStop.");
        }
    

You can also override the OnPause, OnContinue, and OnShutdown methods to define additional processing for your component.

To define other actions for the service

  • For the method that 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:

    Visual Basic
    Protected Overrides Sub OnContinue()
      EventLog1.WriteEntry("In OnContinue.")
    End Sub
    
    C#
        protected override void OnContinue()
        {
            eventLog1.WriteEntry("In OnContinue.");
        }  
    

Some custom actions have to occur when a Windows service is installed, 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. In Solution Explorer, right-click Service1.vb or Service1.cs and select View Designer.

  2. Click the background of the designer to select the service itself, instead of any of its contents.

  3. With the designer in focus, right-click, and then click Add Installer.

    By default, a component class that contains 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. In Design view for ProjectInstaller, click ServiceInstaller1 for a Visual Basic project, or serviceInstaller1 for a Visual C# project.

  5. In the Properties window, make sure the ServiceName property is set to MyNewService.

  6. Set the StartType property to Automatic.

  7. In the designer, click ServiceProcessInstaller1 for a Visual Basic project, or serviceProcessInstaller1 for a Visual C# project. Set the Account property to LocalSystem. This will cause the service to be installed and to run on a local service account.

    Security noteSecurity Note

    The LocalSystem account has broad permissions, including the ability to write to the event log. Use this account with caution, because it might increase your risk of attacks from malicious software. For other tasks, consider using the LocalService account, which acts as a non-privileged user on the local computer and presents anonymous credentials to any remote server.

To build your service project

  1. In Solution Explorer, right-click your project and then click Properties. The project's Property Designer appears.

  2. On the Application page, from the Startup object list, click MyNewService.Program.

  3. Press CTRL+SHIFT+B to build the project.

Now that the project is built, it can be deployed. A setup project will install the compiled project files and run the installers that are required to run the Windows service. To create a complete setup project you will have to add the project output, MyNewService.exe, to the setup project and then add a custom action to have MyNewService.exe installed. For more information about setup projects, see Setup and Deployment Projects. For more information about custom actions, see Walkthrough: Creating a Custom Action.

To create a setup project for your service

  1. In Solution Explorer, right-click your solution node (not the project node), point to Add, and then click New Project.

  2. Under Installed Templates, expand Other Project Types and then expand Setup and Deployment.

  3. Select Visual Studio Installer.

  4. In the Templates pane, select Setup Project. Name the project MyServiceSetup. Click OK.

    A setup project is added to the solution.

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

To add MyNewService.exe to the setup project

  1. In Solution Explorer, right-click MyServiceSetup, point to Add, and then click Project Output.

    The Add Project Output Group dialog box appears.

  2. MyNewService is selected in the Project box.

  3. From the list, 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, and then click Custom Actions.

    The Custom Actions editor appears.

  2. In the Custom Actions editor, right-click the Custom Actions node and click Add Custom Action.

    The Select Item in Project dialog box appears.

  3. Double-click the Application Folder in the list 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. In Solution Explorer, right-click the MyServiceSetup project and click Build.

To install the Windows Service

  1. To install MyNewService.exe, right-click the setup project in Solution Explorer and select Install.

  2. Follow the steps in the Setup Wizard. Build and save your solution.

To start and stop your service

  1. To open the Services Control Manager in Windows 7, Windows Vista, and Windows Server, right-click Computer on the Start menu, and then click Manage. In the Computer Management console, expand the Services and Applications node in the left pane. Click Services.

    You should now see MyNewService listed in the Services section of the window.

  2. Select your service in the list, right-click it, and then click Start.

  3. Right-click the service, and then click Stop.

To verify the event log output of your service

  1. Open Server Explorer and access the Event Logs node.

  2. Locate the listing for MyNewLog and expand it. You should see entries for the actions your service has performed.

To uninstall your service

  • On the Start menu, open Control Panel and click Add or Remove Programs, and then locate your service and click Uninstall.

You might explore the use of a ServiceController component to enable you to send commands to the service you have installed.

You can use an installer to create an event log when the application is installed instead of creating the event log when the application runs. Additionally, the event log will be deleted by the installer when the application is uninstalled.

Date

History

Reason

July 2011

Corrected and clarified several points.

Customer feedback.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
IMPORTANT: if install appears to work but you can't see the service...      jason027   |   Edit   |   Show History

If ever you are building a windows service in VS 2010 and you are about to create a installer for it, just before you add output to the installer, do this...

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.
If you skip these steps, your setup project will build and copy your files to the correct directory; however, they will not register your binary as a service without these steps.

Tags What's this?: Add a tag
Flag as ContentBug
Something missing from Setup Project      Bernhard E   |   Edit   |   Show History
With the service started as Local System, APPDATA for the Setup Project does not point to the same place as APPDATA does for the service. This makes it necessary to make assumptions as to where to put config/data files the service uses and modifies. The service will (on win7) access this folder:

C:\Windows\System32\config\systemprofile\AppData\Roaming

The Setup Project will access the user's application data folder here:

C:\Users\<user>\AppData\Roaming

I can't find a way to preset the user for the Setup Project to match the service (Local System).

Edit: Just discovered that the actual path being used is this (the service has no idea):

C:\Windows\SysWOW64\config\systemprofile\AppData\Roaming

How I should make the Setup Project adapt I have no idea.

Tags What's this?: Add a tag
Flag as ContentBug
Add Project Output Group dialogue is empty      Robin CM   |   Edit   |   Show History
When I try and add the service project to the setup project via the Add Project Output Group dialogue box, not only is the Service project not listed, but there is nothing available in the list to pick at all.
Tags What's this?: Add a tag
Flag as ContentBug
Missing Solution Node?      Robin CM   |   Edit   |   Show History

Have just discovered that you can make the Solution Node show by going to Tools, Options, Projects and Solutions, General and ticking the box "Always Show Solution".

Then the instructions for adding the setup project, and adding the service to it via the Add Project Output Group dialogue work as described.

Tags What's this?: Add a tag
Flag as ContentBug
Adding new project to solution node      Lauren Bish   |   Edit   |   Show History
For those having problems with this step, the walkthrough doesn't mention that any solution opened in VS 2010 that doesn't have more than one project will NOT show the Solution Node. So you can't click on it. You are trying to add to some other node - probably the Project Node. Which is why you can't see the projects types as described.$0 $0 To get past this, go to the main File menu, select New, select Project and then follow the instructions in the Walkthrough.$0 $0 The walkthrough should add this as a note/sidebar/something.
Tags What's this?: Add a tag
Flag as ContentBug
Cant get service to run      HallJam ... jshovelt   |   Edit   |   Show History
I have done every step as listed and the service does not show up. I can go see that the apllication installed but i do not the service listed. Has anyone seen this before? $0$0 $0 $0- Yes, that happened to me. It turned out that although I had renamed it "MyNewService" I eventually found it in the services list as "Service1". Turns out you have to rename in other places, not just the filename. Hope that helps. $0
Tags What's this?: Add a tag
Flag as ContentBug
Error 1053 (Service does not start)      Oekiwoeki ... Thomas Lee   |   Edit   |   Show History
Found on http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx?msg=2078844

Error 1053 : "the service did not respond to start or control request in timely fashion"

Restart didn't help.. What did help, however, is once the service is installed, run services.msc, rightclick MyNewService, choose Properties, click on Log On tab, and change the "Log on as " radio selection from "This account" (which is the NT Authority) to "Local System Account" (I left "Allow service to interact with desktop" unchecked.) and OK. Then, trying to run the service works..
Tags What's this?: Add a tag
Flag as ContentBug
Awesome post      OrlanduMike ... Thomas Lee   |   Edit   |   Show History
Awesome post! Clear and exactly what I needed.

Thanks
Tags What's this?: Add a tag
Flag as ContentBug
Small update      OrlanduMike ... Thomas Lee   |   Edit   |   Show History
Not a big thing, but I got confused (since I was doing it with real name of my project)

Step: To build your service project

In Solution Explorer, right-click your project and then click Properties. The project's Property Designer appears.

On the Application page, from the Startup object list, click wrong: MyNewService. what I seen: MyNewService.Program

Press CTRL+SHIFT+B to build the project.
Tags What's this?: Add a tag
Flag as ContentBug
problem with installer setup...?      Kevison ... Thomas Lee   |   Edit   |   Show History
To build our service project

In Solution Explorer, right-click your project and then click Properties. The project's Property Designer appears.

On the Application page, from the Startup object list, click MyNewService.

Press CTRL+SHIFT+B to build the project.

The above does not seem to work with any Windows Service I create.... the only thing in the startup object is program.cs
Tags What's this?: Add a tag
Flag as ContentBug
Errors on installing service      joneschrisan ... Thomas Lee   |   Edit   |   Show History
I get errors when trying to install the service, the wizard runs and then after windows asking my to give permission to the installer to change my computer it asks me to "Set Service Login" with 'Username', 'Password' and 'Confirm Password'.
Now if I type in the name of the service and then some password I get this error message:
Error 101. No mapping between account names and security IDs was done
But if I type in my own windows username and then the correct password I get this error:
0Error 1001. The account name is invalid or does not exist, or the password is invalid for the account name specified
Any one know what's going on or how to continue past this point?
Also where it tells you to right click in the solution and then add .... try clicking 'File->Add->New Project' don't know why it doesn't come up when you right click on the solution explorer.
As for the 'To add custom event log functionality to your service'
I changed the code to this and it didn't give me the 'unhandled&;;nbsp;security exception' any more.
Public Sub New()
MyBase.New()
InitializeComponent()
Try
If Not System.Diagnostics.EventLog.SourceExists("mySource") Then
System.Diagnostics.EventLog.CreateEventSource("mySource", "myNewLog")
End If
EventLog1.Source = "mySource"
EventLog1.Log = "myNewLog"
Catch ex As Exception
Try
System.Diagnostics.EventLog.CreateEventSource("mySource", "myNewLog")
EventLog1.Source = "mySource"
EventLog1.Log = "myNewLog"
Catch ex2 As Exception
'Do nothing.
End Try
End Try
End Sub

To Solve this:

Change the account property to "LocalSystem" in the serviceprocessinstaller.
Tags What's this?: Add a tag
Flag as ContentBug
Not able to create setup project in my service.      Reyansh ... BobGibsonmrp   |   Edit   |   Show History
I really don't find any way to add the setup project in my service. In Solution Explorer, right-click your solution, point to Add, and then click New Project. Add is not allowing me to add any projects instead it allows me to add items. Am I missing something here?

I think you are selecting the project from Solution Explorer. You need to select the solution, then you can add another project.
I hope this helps.
Tags What's this?: Add a tag
Flag as ContentBug
One of the most comprehensive guides I've seen      hikizume   |   Edit   |   Show History
More of these walkthroughs should be like this
Tags What's this?: Add a tag
Flag as ContentBug
Empty Setup Projects Template      Mark Wardell   |   Edit   |   Show History
On the Step Below I had no templates on my VSNet 2010 Professional....

Why...Oh does anyone answer here?


Under Installed Templates, expand Other Project Types and then expand Setup and Deployment.

Select Visual Studio Installer.

In the Templates pane, select Setup Project. Name the project MyServiceSetup. Click OK.
A setup project is added to the solution.
Next you will add the output from the Windows service project, MyNewService.exe, to the setup.
Tags What's this?: Add a tag
Flag as ContentBug
notes: regarding "To add custom event log functionality to your service"      gerry lowry   |   Edit   |   Show History
(a) one may right click the EventLog in the designer view and click
Properties to assign it a more meaningful name; otherwise,
it will be called something like "eventLog1".

(b) it appears (at least for me on Windows 7) that Source can not be set manually
in the Properties window; this is likely some form of rights issue.
For that reason, as seen in the example code,
the following statements have be given:

eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
Tags What's this?: Add a tag
Flag as ContentBug
typo? "Access the Windows ==> 2000 <== Services Control Manager ..."      gerry lowry   |   Edit   |   Show History
-- Access the Windows 2000 Services Control Manager and start your service.

--???? Windows 2000 ???$

--should probably be simply (drop the "2000"):

--"Access the Windows Services Control Manager and start your service."

[the editor for Community Content does not behave well in Google Chrome.]
Tags What's this?: Add a tag
Flag as ContentBug
Windows Service project template for VS 2010      scottxxxxxxxxxxxxxxxxxxxxxxxxxxx   |   Edit   |   Show History
Its a disservice to us all to have this page for VS 2010 if indeed the Windows Service project template has been removed for C++. Just say so here if this is the case.
Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2012 Microsoft. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker