Create a Windows service using C #

Source: Internet
Author: User

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:

usingSystem;usingsystem.serviceprocess;usingSystem.IO;namespacemywindowsservice{ Public Partial classMyservice:servicebase { PublicMyService () {InitializeComponent (); }        stringFilePath =@"D:\MyServiceLog.txt"; protected Override voidOnStart (string[] args) {            using(FileStream stream =NewFileStream (filepath,filemode.append))using(StreamWriter writer =NewStreamWriter (Stream)) {writer. WriteLine ($"{DateTime.Now}, service started! "); }        }        protected Override voidOnStop () {using(FileStream stream =NewFileStream (FilePath, filemode.append))using(StreamWriter writer =NewStreamWriter (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:

usingSystem;usingSystem.Collections;usingSystem.Windows.Forms;usingsystem.serviceprocess;usingSystem.Configuration.Install;namespacewindowsserviceclient{ Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); }        stringServicefilepath = $"{Application.startuppath}\\mywindowsservice.exe"; stringServiceName ="MyService"; //Event: Installation Service        Private voidButton1_Click (Objectsender, EventArgs e) {            if( This. Isserviceexisted (ServiceName)) This.            Uninstallservice (ServiceName);  This.        Installservice (Servicefilepath); }        //event: Start service        Private voidButton2_Click (Objectsender, EventArgs e) {            if( This. Isserviceexisted (ServiceName)) This.        Servicestart (ServiceName); }        //Event: Stop service        Private voidButton4_Click (Objectsender, EventArgs e) {            if( This. Isserviceexisted (ServiceName)) This.        Servicestop (ServiceName); }        //Event: Uninstalling the service        Private voidButton3_Click (Objectsender, EventArgs e) {            if( This. Isserviceexisted (ServiceName)) { This.                Servicestop (ServiceName);  This.            Uninstallservice (Servicefilepath); }        }        //determine if a service exists        Private BOOLIsserviceexisted (stringserviceName) {servicecontroller[] Services=servicecontroller.getservices (); foreach(ServiceController SCinchservices) {                if(SC. Servicename.tolower () = =Servicename.tolower ()) {                    return true; }            }            return false; }        //Installation Services        Private voidInstallservice (stringServicefilepath) {            using(Assemblyinstaller installer =NewAssemblyinstaller ()) {Installer. Usenewcontext=true; Installer. Path=Servicefilepath; IDictionary savedstate=NewHashtable (); Installer.                Install (savedstate);            Installer.Commit (savedstate); }        }        //Uninstall Service        Private voidUninstallservice (stringServicefilepath) {            using(Assemblyinstaller installer =NewAssemblyinstaller ()) {Installer. Usenewcontext=true; Installer. Path=Servicefilepath; Installer. Uninstall (NULL); }        }        //Start the service        Private voidServicestart (stringserviceName) {            using(ServiceController control =NewServiceController (ServiceName)) {                if(Control. Status = =servicecontrollerstatus.stopped) {control.                Start (); }            }        }        //Stop Service        Private voidServicestop (stringserviceName) {            using(ServiceController control =NewServiceController (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:

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:

Reprinted from: http://www.cnblogs.com/cncc/p/7170951.html

Create a Windows service using C #

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.