How does the Windows service be created under C #?

Source: Internet
Author: User
This article mainly introduces the use of C # to create a Windows service instance code, small series feel very good, and now share to everyone, but also for everyone to make a reference. Let's take a look at it with a little knitting.

This article describes the example code for creating a Windows service using C # and sharing it to everyone

First, the development environment

Operating system: Windows ten X64

Development environment: VS2015

Programming Language: C #

. NET version:. NET Framework 4.0

Target platform: X86

Second, create Windows Service

1. Create a new Windows Service and change the project name to "Mywindowsservice" as shown in:

2. In Solution Explorer, change Service1.cs to MyService1.cs and click the "View Code" icon button to enter the Code Editor interface as shown in:

3. In the Code Editor, enter the following code as follows:

Using system;using system.serviceprocess;using system.io;namespace mywindowsservice{public  partial class Myservice:servicebase  {public    myservice ()    {      InitializeComponent ();    }    String filePath = @ "D:\MyServiceLog.txt";    protected override void OnStart (string[] args)    {      using (FileStream stream = new FileStream (FilePath, filemode.append))      using (StreamWriter writer = new StreamWriter (stream))      {        writer. WriteLine ($ "{DateTime.Now}, service started! ");      }    }    protected override void OnStop ()    {      using (FileStream stream = new FileStream (FilePath, Filemode.append))      using (StreamWriter writer = new StreamWriter (stream))      {        writer. WriteLine ($ "{DateTime.Now}, service stopped! ");      }    }  }}

4, double-click the project "Mywindowsservice" into the "MyService" design interface, in the blank position right click the mouse Popup context menu, select "Add Installer", as shown in:

5, the software will generate two components, respectively, "ServiceInstaller1" and "ServiceProcessInstaller1", as shown:

6, click "ServiceInstaller1", in the "Properties" form change ServiceName to myservice,description to my service, StartType remains as manual as shown:

7. Click "ServiceProcessInstaller1" in the "Properties" form to change the account to LocalSystem (Service attribute system level) as shown in:

8, right click on the item "Mywindowsservice", in the Popup context menu, select the "Generate" button, as shown in:

9. At this point, the Windows service has been created.

Iii. Creating Windows Forms for installing, starting, stopping, and uninstalling services

1. Create a new Windows Form project in the same solution and name it as Windowsserviceclient, as shown in:

2. Set the project as the startup project and add four buttons to the form to install the service, start the service, stop the service, and uninstall the service, as shown in:

3, press F7 Enter the code editing interface, reference "System.ServiceProcess" and "System.Configuration.Install", and enter the following code:

Using system;using system.collections;using system.windows.forms;using system.serviceprocess;using      System.configuration.install;namespace windowsserviceclient{public partial class Form1:form {public Form1 () {    InitializeComponent ();    } string Servicefilepath = $ "{Application.startuppath}\\mywindowsservice.exe";    String serviceName = "MyService"; Event: Installation service private void button1_click (object sender, EventArgs e) {if (this. Isserviceexisted (ServiceName)) this.      Uninstallservice (ServiceName); This.    Installservice (Servicefilepath); }//Event: Start service private void button2_click (object sender, EventArgs e) {if (this. Isserviceexisted (ServiceName)) this.    Servicestart (ServiceName); }//Event: Stop service private void Button4_Click (object sender, EventArgs e) {if (this. Isserviceexisted (ServiceName)) this.    Servicestop (ServiceName); }//Event: Unload service private void Button3_Click (object sender, EventArgs e) {if (this. Isserviceexisted (SERvicename)) {this.        Servicestop (ServiceName); This.      Uninstallservice (Servicefilepath); }}//Determine if the service exists private bool Isserviceexisted (string serviceName) {servicecontroller[] services = Service      Controller.getservices (); foreach (ServiceController sc in services) {if (SC.        Servicename.tolower () = = Servicename.tolower ()) {return true;    }} return false; }//Installation service private void Installservice (string servicefilepath) {using (Assemblyinstaller installer = new Asse Mblyinstaller ()) {installer.        Usenewcontext = true; Installer.        Path = Servicefilepath;        IDictionary savedstate = new Hashtable (); Installer.        Install (savedstate);      Installer.Commit (savedstate); }}//unload service private void Uninstallservice (string servicefilepath) {using (Assemblyinstaller installer = n EW Assemblyinstaller ()) {installer.        Usenewcontext = true; InsTaller.        Path = Servicefilepath; Installer.      Uninstall (NULL); }}//Start service private void Servicestart (string serviceName) {using (ServiceController control = new service Controller (ServiceName)) {if (control. Status = = servicecontrollerstatus.stopped) {control.        Start (); }}}//stop service private void Servicestop (string serviceName) {using (ServiceController control = new S Ervicecontroller (ServiceName)) {if (control. Status = = servicecontrollerstatus.running) {control.        Stop (); }      }    }  }}

4, for the subsequent debugging services and the need to install the uninstall service, the generated MyWindowsService.exe reference to this Windows Form, as shown in:

5, due to the need to install services, it is necessary to use the UAC administrator permissions, the mouse right click on the project "Windowsserviceclient", in the context menu pop-up Select "Add", "New Item", in the pop-up selection form, select " Application manifest file and click OK as shown in:

6. Open the file and change <requestedexecutionlevel level= "AsInvoker" uiaccess= "false"/> to <requestedexecutionlevel level= "Requireadministrator" uiaccess= "false"/>, as shown in:

7. After the IDE starts, the form shown below will pop up (some systems may not be displayed due to UAC configuration) and need to be opened with Administrator privileges:

8. After re-opening, run the Windowsserviceclient project in the IDE;

9. Use Win+r to open the running form and open the service after entering services.msc in the body, as shown in:

10, click the "Install Service" button in the window, will appear in the service MyService, as shown:

11. Click the "Run Service" button to start and run the service as follows:

12. Clicking the "Stop Service" button will stop the service from running, as shown in:

13. Click the "Uninstall Service" button and the MyService service will be removed from the service.

14, the above start and stop services will be written to D:\MyServiceLog.txt, the contents are as follows:

Source code Download: Mywindowsservice_jb51.rar

Add: How to debug a service

1, to debug the service, in fact, is very simple, if you need to attach the service to the project needs to debug inside can, if you want to debug the service just built, now OnStop event set breakpoints, as follows:

2. Start the "Windowsserviceclient" project and select "attachment to Process" in the "Debug" menu (the service must be installed beforehand) as follows:

3, find "MyWindowsService.exe", click "Attach" button, as shown:

4. Click the "Stop Service" button and the program will break at the place where you set the breakpoint, as shown in:

Related Article

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.