Megosztás a következőn keresztül:


Walkthrough: Creating a Windows Service Application in the Component Designer

Note

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 2000 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.

Note

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.

Creating a Service

To create and configure your service

  1. On the File menu, click New Project.

    The New Project dialog box opens.

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

    Note

    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.

  4. Set the AutoLog property to true.

  5. On the View menu, click Code to open 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. In Visual C# applications, the Main method is located in the Program.cs file.

    ' To access the Main method in Visual Basic, select Main from the 
    ' method name drop-down list. This expands the Component Designer  
    ' generated code region. 
    Shared Sub Main()
      Dim ServicesToRun() As System.ServiceProcess.ServiceBase
      ' Change the following line to match.
      ServicesToRun = New System.ServiceProcess.ServiceBase() _
          {New MyNewService()}
      System.ServiceProcess.ServiceBase.Run(ServicesToRun)
    End Sub
    
    static void Main()
        {
            System.ServiceProcess.ServiceBase[] ServicesToRun;
            // Change the following line to match.
            ServicesToRun = new System.ServiceProcess.ServiceBase[] 
              { new MyNewService() };
            System.ServiceProcess.ServiceBase.Run(ServicesToRun);
        }
    

Adding Features to the Service

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. For more information about custom event logs, see How to: Create and Remove Custom Event Logs.

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. Edit the constructor to define a custom event log.

    ' 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
    
    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:

    ' 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
    
    protected override void OnStart(string[] args)
        {
            eventLog1.WriteEntry("In OnStart");
        }
    

    Note

    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:

    Protected Overrides Sub OnStop()
      EventLog1.WriteEntry("In OnStop.")
    End Sub
    
    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:

    Protected Overrides Sub OnContinue()
      EventLog1.WriteEntry("In OnContinue.")
    End Sub
    
    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 or serviceInstaller1.

  5. In the Properties window, set the ServiceName property 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.

  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 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 to select your solution, point to Add, and then click 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. 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. Open the Services Control Manager by doing one of the following:

    • In Windows XP and 2000 Professional, right-click My Computer on the desktop, and then click Manage. In the Computer Management console, expand the Services and Applications node.

      - or -

    • In Windows Server 2003 and 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.

    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. For more information, see How to: Work with Event Logs in Server Explorer.

    Note

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

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

To uninstall your service

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

  2. You can also uninstall the program by right-clicking the program icon for the .msi file and selecting Uninstall.

    Note

    If you installed the service on Windows 2000, you will have to restart the system before you can reinstall the service. In Windows 2000, services are not completely deleted until the system is rebooted.

Next Steps

You might explore the use of a ServiceController component to enable you to send commands to the service you have installed. For more information about using the ServiceController component, see Monitoring Windows Services.

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. For more information, see Walkthrough: Installing an Event Log Component.

See Also

Tasks

How to: Add Installers to Your Service Application

How to: Install and Uninstall Services

How to: Debug Windows Service Applications

How to: Launch Event Viewer from the Server Explorer

Concepts

Introduction to Windows Service Applications

Reference

How to: Access and Initialize Server Explorer/Database Explorer

Other Resources

Windows Service Applications

Change History

Date

History

Reason

February 2009

Revised descriptions of account settings.

Customer feedback.