Click here to Skip to main content
15,919,613 members
Articles / Programming Languages / C#
Article

How to Write Windows Service and Control It By Application

Rate me:
Please Sign up or sign in to vote.
2.00/5 (6 votes)
17 Mar 2008CPOL2 min read 70.1K   684   39   4
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).

      C#
      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:

      C#
      [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:
    C#
             ...  
    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)


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

Comments and Discussions

 
QuestionUmmm... what? Pin
PIEBALDconsult17-Mar-08 7:43
mvePIEBALDconsult17-Mar-08 7:43 
AnswerRe: Ummm... what? Pin
Laker17-Mar-08 17:44
Laker17-Mar-08 17:44 
GeneralNot the recommended way Pin
evolved17-Mar-08 6:25
evolved17-Mar-08 6:25 
You should take a look at using remoting to control a .net service. You use remoting as usual, MarshalByRef objects, get a reference to your service instance, and then call methods, etc to it from your application.
Getting the guts working takes a bit of understanding on the remoting end, but it's worth it.
GeneralRe: Not the recommended way Pin
MKauffman17-Mar-08 6:42
MKauffman17-Mar-08 6:42 

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.