To create a Windows service program in Visual C #

Source: Internet
Author: User
Tags command line file system include modify new features variables visual studio
visual|window| Program | create one. Windows Services Introduction:

Windows Services, formerly known as NT Services, are programs that run outside of the user environment under operating systems such as Windows NT, Windows 2000, and Windows XP. In the past, writing windows Service ProgramProgrammers need strong C or C + + skills. Now, however, under Visual Studio.NET, you can use C + + or visual C #Or Visual Basic.NET is easy to create a Windows Service Program。 Similarly, you can use any other language that is compatible with the CLR to create Windows Service Program。 This article will introduce you how to use visual C #To create one step at a a file monitor windows Service Program, and then describes how to install, test, and debug the Windows Service Program

When you describe how to create windows Service ProgramBefore, let me introduce some background knowledge about Windows services. A Windows Service Programis an executable application that can perform specific functions under the Windows operating system. Windows Service ProgramAlthough it is executable, it is not like a normal executable file can start running by double-clicking it, it must have a specific startup mode. These boot modes include automatic startup and manual startup. For Windows that start automatically Service Program, they begin executing before the user logs on after Windows starts or restarts. As soon as you will be corresponding to the Windows Service ProgramRegister to the Service Control Manager and set its startup category to start automatically on the line. For windows that are manually started Service Program, you can use the command line tool's net START command to start it, or start the appropriate Windows by using a service item under Administrative Tools in Control Panel Service Program(see Figure 1). Similarly, a Windows Service ProgramNor can it be terminated as an ordinary application. Because Windows Service ProgramGenerally there is no user interface, so you also need to use command-line tools or the tools in the following diagram to stop it, or when the system shuts down to make Windows Service ProgramAutomatically stop. Because Windows Service ProgramWithout a user interface, API functions based on the user interface have little meaning. In order to make a Windows Service ProgramTo work properly and effectively in a system environment, programmers must implement a series of methods to perform their service functions. Windows Service ProgramA wide range of applications, a typical Windows Service ProgramIncludes features such as hardware control, application monitoring, system-level applications, diagnostics, reporting, Web and file system services.

Figure 1



   two. To create a Windows Service program :

When you describe how to create windows Service ProgramBefore, let me introduce to you. NET Framework, the Windows service-related namespaces and the class libraries in them. NET Framework greatly simplifies the windows Service ProgramProcess of creation and control, thanks to the powerful class libraries in its namespaces. and Windows Service ProgramThe related namespaces involve the following two: System.ServiceProcess and System.Diagnostics.

To create one of the most basic windows Service Program, we just need to use. NET Framework of the System.ServiceProcess namespace and its four classes: ServiceBase, ServiceInstaller, ServiceProcessInstaller and ServiceController, the architecture is visible in Figure 2.

Figure 2



Where the ServiceBase class defines a number of functions that can be overloaded by its subclasses, the Service Control Manager can control the Windows Service ProgramOut. These functions include: OnStart (), OnStop (), OnPause (), and OnContinue () four. Also, subclasses of the ServiceBase class can overload the Oncustomcommand () function to perform certain operations. By overloading some of the above functions, we have completed a Windows Service ProgramThe basic framework for the overloaded methods of these functions are as follows:

     
       
        
      protected override void OnStart (string[] args) {}protected override void OnStop () {}protected override void OnPause () {} protected override void OnContinue () {}
     
       


The ServiceBase class also provides us with properties that are any widnows Service Programis necessary. The ServiceName property specifies the name of the Windows service through which the Windows service can be invoked, and other applications can invoke its services by that name. The canpauseandcontinue and CanStop attributes are meant to allow pauses and restores and allow stopping.

To make a Windows Service ProgramTo work properly, we need to create a program entry point for it like a generic application. In Windows Service Program, we do this in the main () function as well. First we create an instance of a Windows service in the main () function, which should be an object of a subclass of the ServiceBase class, and then we call a run () method defined by the base class ServiceBase class. However, the run () method does not start with Windows Service Program, we must use the Service Control Manager mentioned earlier to invoke the specific control function to complete the windows Service ProgramStart, that is, the service does not really start until the OnStart () method of the object is invoked. If you want to be in a Windows Service ProgramTo start multiple services at the same time in the main () function, you can define an instance object for the subclasses of multiple servicebae classes by creating an array object of the ServiceBase class that corresponds to a service that we have predefined.

     
        
         
      {system.serviceprocess.servicebase[] myservices; MyServices = new system.serviceprocess.servicebase[] {new Service1 (), New Service2 ()}; System.ServiceProcess.ServiceBase.Run (myservices);}
     
        


static void Main ()

   three. To add a file monitoring service:

Once you understand the basic architecture of Windows services and how to create them, we can try to add some actual functionality to the service. I'll introduce you to a file monitoring service-filemonitorservice that monitors the local file system. The service is able to monitor files including any changes in subfolders based on a predetermined local directory path: file creation, file deletion, file name change, file modification. At the same time, the service creates a corresponding counter for each change, and the counter acts as a reflection of the frequency of the change.

First, we open Visual Studio.NET and create a new visual C #The Windows Services project, as shown in Figure 3:

Figure 3



Before overloading the OnStart () function for Windows services, we first add counter objects to its classes, which correspond to changes in the creation, deletion, renaming, and modification of the file. Once a file in the specified directory has a change above, its corresponding counter is automatically added by 1. All of these counters are variables defined as PerformanceCounter types, which are contained within the System.Diagnostics namespace.

     
         
          
      Private System.Diagnostics.PerformanceCounter filecreatecounter;private System.Diagnostics.PerformanceCounter Filedeletecounter;private System.Diagnostics.PerformanceCounter Filerenamecounter;private System.Diagnostics.PerformanceCounter Filechangecounter;
     
         


We then create the individual counter objects defined above in the InitializeComponent () method of the class and determine their associated properties. At the same time, we set the name of the Windows service to "Filemonitorservice" and set it to allow pauses and restores to be allowed to stop.

          
           
private void InitializeComponent () {this.components = new System.ComponentModel.Contain                     ER ();                     This.filechangecounter = new System.Diagnostics.PerformanceCounter ();                     This.filedeletecounter = new System.Diagnostics.PerformanceCounter ();                     This.filerenamecounter = new System.Diagnostics.PerformanceCounter ();                     This.filecreatecounter = new System.Diagnostics.PerformanceCounter ();                     Filechangecounter.categoryname = "File Monitor Service";                     Filedeletecounter.categoryname = "File Monitor Service";                     Filerenamecounter.categoryname = "File Monitor Service";                     Filecreatecounter.categoryname = "File Monitor Service";                     Filechangecounter.countername = "Files Changed";                     Filedeletecounter.countername = "Files Deleted"; Filerenamecounter.countername = "Files renamed";                     Filecreatecounter.countername = "Files Created"; This.                     ServiceName = "Filemonitorservice"; This.                     CanPauseAndContinue = true; This.                     CanStop = true;              servicepaused = false; }
          


Then there is the overloaded OnStart () function and the OnStop () function, and the OnStart () function completes some of the necessary initialization work. Under the. NET Framework, the monitoring capability of a file can be done by the FileSystemWatcher class, which is contained under the System.IO namespace. The functionality that the Windows service will complete includes changes to the creation, deletion, renaming, and modification of the monitoring file, and the FileSystemWatcher class contains all the processing functions that correspond to these changes.

 
           
             protected override void OnStart (                     String[] args {FileSystemWatcher curwatcher = new FileSystemWatcher ();                     Curwatcher.begininit ();                     Curwatcher.includesubdirectories = true; Curwatcher.path = System.Configuration.ConfigurationSettings.AppSettings ["Filemonitordirectory"                     ];                     Curwatcher.changed + = new FileSystemEventHandler (onfilechanged);                     curwatcher.created + = new FileSystemEventHandler (onfilecreated);                     curwatcher.deleted + = new FileSystemEventHandler (onfiledeleted);                     Curwatcher.renamed + = new Renamedeventhandler (onfilerenamed);                     Curwatcher.enableraisingevents = true;              Curwatcher.endinit (); }
     
           


Note that the directory being monitored is stored in an application configuration file, which is an XML-type file. The advantage of this approach is that we do not have to recompile and publish the Windows service and simply modify its configuration file to achieve the ability to change the directory to be monitored.

When the Windows service starts, once a file in the monitored directory changes, the value of its corresponding counter increases, and the method is simple, as long as the IncrementBy () of the Counter object is invoked.

            
             
private void onfilechanged (Object source, FileSystemEventArgs e) {if (servicepaused = =                     False) {Filechangecounter.incrementby (1);                     } private void Onfilerenamed (Object source, RenamedEventArgs e) {                     if (servicepaused = = False) {Filerenamecounter.incrementby (1);                     } private void onfilecreated (Object source, FileSystemEventArgs e) { if (servicepaused = = False) {Filecreatecounter.increment                     by (1);                     } private void onfiledeleted (Object source, FileSystemEventArgs e) {                    if (servicepaused = = False) {Filedeletecounter.incrementby (1); }              } 
            


The OnStop () function is to stop the Windows service, in which the value of all counters should be zero when the service is stopped, but the counter does not provide a reset () method, so we have to subtract the current value from the counter to achieve this goal.

     
             
              
      protected override void OnStop ()              {                     if (filechangecounter.rawvalue!= 0)                     {                            Filechangecounter.incrementby (-filechangecounter.rawvalue);                     }                     if (filedeletecounter.rawvalue!= 0)                     {                            filedeletecounter.incrementby (-filedeletecounter.rawvalue);                     }                     if (filerenamecounter.rawvalue!= 0)                     {                            Filerenamecounter.incrementby (-filerenamecounter.rawvalue);                           }                     if (filecreatecounter.rawvalue!= 0)                     {                            filecreatecounter.incrementby (-filecreatecounter.rawvalue);                     }              }
     
             


Also, because our Windows service is allowed to pause and recover, we also have to overload the OnPause () function and the oncontinue () function simply by setting the previously defined Boolean value servicepaused.

     
              
               
      protected override void OnPause ()              {                     servicepaused = true;              }             protected override void OnContinue ()              {                     servicepaused = false;             }
     
              


In this way, the main part of the Windows service is complete, but it is not useful and we must also add the installation files for it. The installation file works well for the proper installation of the Windows service, which includes the installation class for a Windows service that is heavily System.Configuration.Install.Installer inherited. The installation class includes information such as account information, user name, password information, and the name of the Windows service, how to start, and so on, for the Windows service to run.

               
                
[Runinstaller (true)] public class Installer1:System.Configuration.Install.Installer {///<              Summary>///required designer variables.              </summary> private System.ComponentModel.Container components = null;              Private System.ServiceProcess.ServiceProcessInstaller Spinstaller;              Private System.ServiceProcess.ServiceInstaller Sinstaller;                     Public Installer1 () {//This call is required by the designer.                    InitializeComponent ();  TODO: Add any initialization} after the initcomponent call #region Component Designer generated code///              <summary>///Designer supports the desired method-do not use the Code Editor to modify the contents of///this method. </summary> private void InitializeComponent () {components = new Sy Stem.                     Componentmodel.container (); Creating ServiceProcessInstaller objects and ServiceinsTaller Object This.spinstaller = new System.ServiceProcess.ServiceProcessInstaller ();                     This.sinstaller = new System.ServiceProcess.ServiceInstaller (); Set the ServiceProcessInstaller object's account number, username and password This.spInstaller.Account = System.servicepro Cess.                     Serviceaccount.localsystem;                     This.spInstaller.Username = null;     This.spInstaller.Password = null;     Set service Name This.sInstaller.ServiceName = "Filemonitorservice"; Set how the service starts This.sInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automati                     C This. Installers.addrange (new system.configuration.install.installer[] {this.spinstaller, this.sin              Staller}); } #endregion}
               


Similarly, because the counter object is used in the Windows service, we also add the appropriate installation file for it, and the installation file has the same content and function as before. Limited to space, here does not give the corresponding code, interested readers can refer to the source code file with the text.

So far, the entire Windows service has BuildFinished, but Windows Service ProgramUnlike a typical application, it cannot be debugged directly. If you try to run it directly under the IDE, you will be prompted as shown in Figure 4.

Figure 4



According to the prompts, we know that a command-line tool named InstallUtil.exe is needed to install the Windows service. The way to install Windows services with this tool is very simple, and the commands for installing the Windows service are as follows:

     
                
                 
      InstallUtil FileMonitorService.exe
     
                


To uninstall the Windows service, you can simply enter the following command:

 
                  
                    installutil/u FileMonitorService.exe 
                   


Windows service after the installation is successful, it appears in the service control Manager, as shown in Figure 5.

Figure 5



so that the Windows service that the file monitors is complete, and once we operate on the files in the monitored directory, the corresponding counters will function to monitor the changes in the file. However, this feature does not make much sense to the average user, but you can add new features on this basis, such as build a background file processing system, once the monitored directory of the file changes, the Windows service to its specific operation, The end user does not have to care about how the spooler is implemented.

Four. Summary:

This article describes some of the basic concepts of Windows services and the methods needed to build general Windows Services, and also shows you a file monitoring feature of Windows strong> Service . In this article, readers should be able to appreciate that the build Windows service is not as complicated as it is supposed to be, thanks largely to. NET Framework has made a lot of effort for us. At the same time, I hope you can build a more complete and powerful Windows service program based on the examples given in this article. Finally, I hope this article will help you a lot.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.