Click here to Skip to main content
11,705,453 members (34,063 online)
Click here to Skip to main content

How to Write Windows Service and Control It By Application

, 17 Mar 2008 CPOL 48.1K 563 39
Rate this:
Please Sign up or sign in to vote.
Guide to write Windows service and control it by application

Introduction

This article presents the guide to write a Windows service program and control it from another program.

Background

Many projects which I was part of needed the program running as a Windows service. It can auto startup when Windows Restarts and access Domain resource when it runs under special user. But sometimes, Windows service program is not easy to control and config, for example: I need the Windows service running once a day, but maybe I change my idea, need it to run every three hours, so how I config it or make the Windows service more flexible is a puzzle.

Solution

  1. Make Windows service run as it is, making some small modifications to other programs can control it.
  2. Write a small application to control the Windows service.
  3. Use a Windows Scheduler to run the application, config run time as you wish.

Steps

  1. Write a Windows service program (Here, we start to program step by step):

    • Step 1. File -> Project -> Windows C# -> Windows -> Console Application
    • Step 2. Add References to this project:
      • System.Configuration.Install
      • System.ServiceProcess
    • Step 3. Add a new class: SimpleServiceMain.cs (you can rename Program.cs to it, or delete Program.cs, then add a new one).

      public class SimpleServiceMain : ServiceBase
      {
          ....
          protected override void OnCustomCommand(int command)
          {
              // You can add the process which controlled by external program
              OutputDebugString("[SimpleService]" + 
                  "SimpleService OnCustomerCommand
                  (" + command.ToString() + ")");
              base.OnCustomCommand(command);
          } 
          ....
      }  
    • Step 4. Add a new class: SimpleServiceInstall.cs:

      [RunInstaller(true)]
      public class SimpleServiceInstall : Installer
      {
          public SimpleServiceInstall()
          {
              ServiceProcessInstaller serviceProcessInstaller = 
                  new ServiceProcessInstaller();
              ServiceInstaller serviceInstaller = new ServiceInstaller();
          
              //# Service Account Information
              serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
              serviceProcessInstaller.Username = null;
              serviceProcessInstaller.Password = null;
      
              //# Service Information
              serviceInstaller.DisplayName = "SimpleService";
              serviceInstaller.Description = "SimpleService";
              serviceInstaller.StartType = ServiceStartMode.Automatic;
              // This must be identical to the 
              // WindowsService.ServiceBase name
              // set in the constructor of WindowsService.cs
              serviceInstaller.ServiceName = "SimpleService";
              this.Installers.Add(serviceProcessInstaller);
              this.Installers.Add(serviceInstaller);
          }
      }
    • Step 5. Install the Windows service. Here is a batch script to install/uninstall the service:

      Install.bat
      ==============================================================
      ECHO OFF
      REM The following directory is for .NET 2.0
      set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v2.0.50727
      set PATH=%PATH%;%DOTNETFX2%
      echo Installing WindowsService...
      echo ---------------------------------------------------
      InstallUtil /i SimpleService.exe
      sc start SimpleService
      echo ---------------------------------------------------
      echo Done
      pause
      ==============================================================
               
      Unstall.bat
      ==============================================================
      @ECHO OFF
      REM The following directory is for .NET 2.0
      set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v2.0.50727
      set PATH=%PATH%;%DOTNETFX2%
      sc stop SimpleService
      echo Installing WindowsService...
      echo ---------------------------------------------------
      InstallUtil /u SimpleService.exe
      echo ---------------------------------------------------
      echo Done
      pause
      ==============================================================
  2. Write a Windows application to control a Windows service.

    Please make sure that when the application runs, the service has been installed to the system.

    • Step 1. File -> Project -> Windows C# -> Console Application
    • Step 2. Add Reference to this project.
      • System.Configuration.Install
      • System.ServiceProcess
    • Step 3. Add these codes in Program.cs:
             ...  
    static void Main(string[] args)
    {
        string aMachine = "." ;
        string aServiceName = "";
        if( args.Length == 1 ){
            aServiceName = args[0];
        }
        else if (args.Length >= 2)
        {
            aMachine = args[0];
            aServiceName = args[1];
        }
        else
        {
            Console.WriteLine("Error Parameters, 
                the command line should be: ");
            Console.WriteLine("SimpleServiceController ServiceName or");
            Console.WriteLine
                ("SimpleServiceController Machine Name ServiceName");
        }
        System.ServiceProcess.ServiceController sc = 
        new System.ServiceProcess.ServiceController();
        sc.MachineName = aMachine;
        sc.ServiceName = aServiceName;
        sc.ExecuteCommand(130);
    }    
    ...   
  3. How to use Windows Scheduler to control how your program runs. Please read Windows help for more information.

  4. You can use Windows Batch (*.bat) to control multi services by SimpleServiceController.

  5. About OutputDebugString, you can get the tools to view the information: See DebugView for Windows.

History

  • 17th March, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Laker
Software Developer (Senior)
China China
More than 10 years programme experience on C, C++, C#, Delphi.

You may also be interested in...

Comments and Discussions

 
QuestionUmmm... what? Pin
PIEBALDconsult17-Mar-08 7:43
memberPIEBALDconsult17-Mar-08 7:43 
AnswerRe: Ummm... what? Pin
Laker17-Mar-08 17:44
memberLaker17-Mar-08 17:44 
GeneralNot the recommended way Pin
evolved17-Mar-08 6:25
memberevolved17-Mar-08 6:25 
GeneralRe: Not the recommended way Pin
MKauffman17-Mar-08 6:42
memberMKauffman17-Mar-08 6:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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
Web04 | 2.8.150819.1 | Last Updated 17 Mar 2008
Article Copyright 2008 by Laker
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid