C# Create Windows Service (Windows Service) program

1. Development environment

OS: Windows 10 X64

Development environment: VS2015

Programming language: C#

.NET version: .NET Framework 4.0

Target Platform: X86

2. Create Windows Service

1. Create a new Windows Service and change the project name to "MyWindowsService", as shown in the following figure:

2. Change Service1.cs to MyService1.cs in the Solution Explorer and click the "View Code" icon button to enter the code editor interface, as shown in the following figure:

 

 

3. Enter the following code in the code editor, as shown below:

copy code
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!");
            }
        }
    }
}
copy code

4. Double-click the item "MyWindowsService" to enter the "MyService" design interface, right-click the mouse in a blank position to pop up the context menu, and select "Add Installer", as shown in the following figure:

5. At this time, the software will generate two components, namely "serviceInstaller1" and "serviceProcessInstaller1", as shown in the following figure:

6. Click "serviceInstaller1", in the "Properties" window, change the ServiceName to MyService, the Description to my service, and the StartType to be Manual, as shown in the following figure:

7. Click "serviceProcessInstaller1" and change Account to LocalSystem (service property system level) in the "Properties" window, as shown in the following figure:

8. Right-click the project "MyWindowsService", and select the "Generate" button in the pop-up context menu, as shown in the following figure:

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

3. Create Windows Forms for installing, starting, stopping, and uninstalling services

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

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

3. Press F7 to enter the code editing interface, refer to "System.ServiceProcess" and "System.Configuration.Install", and enter the following code:

copy 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: install 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: Uninstall service
        private void button3_Click(object sender, EventArgs e)
        {
            if (this.IsServiceExisted(serviceName))
            {
                this.ServiceStop(serviceName);
                this.UninstallService(serviceFilePath);
            }
        }

        //Check if the service exists
        private bool IsServiceExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController sc in services)
            {
                if (sc.ServiceName.ToLower() == serviceName.ToLower())
                {
                    return true;
                }
            }
            return false;
        }

        //install service
        private void InstallService(string serviceFilePath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceFilePath;
                IDictionary savedState = new Hashtable();
                installer.Install(savedState);
                installer.Commit(savedState);
            }
        }

        //Uninstall the service
        private void UninstallService(string serviceFilePath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceFilePath;
                installer.Uninstall(null);
            }
        }
        // start the service
        private void ServiceStart(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Stopped)
                {
                    control.Start();
                }
            }
        }

        //Out of service
        private void ServiceStop(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Running)
                {
                    control.Stop();
                }
            }
        }
    }
}
copy code

4. For the needs of subsequent debugging services and installation and uninstallation services, reference the generated MyWindowsService.exe to this Windows form, as shown in the following figure:

5. Since you need to install the service, you need to use the Administrator permission in UAC, right-click the item "WindowsServiceClient", select "Add" -> "New Item" in the pop-up context menu, and select " Application Manifest File" and click OK, as shown in the following image:

6. Open the file and change <requestedExecutionLevel level="asInvoker" uiAccess="false" /> to <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />, as shown in the following figure:

7. After the IDE starts, the following window will pop up (some systems may not be displayed due to UAC configuration), you need to open it with administrator privileges:

8. After reopening, run the WindowsServiceClient project in the IDE;

9. Use WIN+R to open the run form, and enter services.msc in the form to open the service, as shown in the following figure:

10. Click the "Install Service" button in the form, and MyService will appear in the service, as shown in the following figure:

11. Click the "Run Service" button to start and run the service, as shown below:

12. Click the "Stop Service" button to stop the running service, as shown in the following figure:

13. Click the "Uninstall Service" button to delete the MyService service from the service.

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

 

Source code download:

 

 

 

Supplement: How to debug a service

1. To debug a service, it is actually very simple. If you need to attach the service process to the project that needs to be debugged, if you want to debug the service you just built, now set a breakpoint in the OnStop event, as shown below:

 

2. Start the "WindowsServiceClient" project and select "Attachment to Process" in the "Debug" menu (the service must be installed in advance), as shown below:

3. Find "MyWindowsService.exe" and click the "Add" button, as shown below:

4. Click the "Stop Service" button, the program will be interrupted at the place where the breakpoint is set, as shown in the following figure:

 

Author: CNXY 
Github: https://www.github.com/cnxy 
Source: http://www.cnc6.cn 

1. Development environment

OS: Windows 10 X64

Development environment: VS2015

Programming language: C#

.NET version: .NET Framework 4.0

Target Platform: X86

2. Create Windows Service

1. Create a new Windows Service and change the project name to "MyWindowsService", as shown in the following figure:

2. Change Service1.cs to MyService1.cs in the Solution Explorer and click the "View Code" icon button to enter the code editor interface, as shown in the following figure:

 

 

3. Enter the following code in the code editor, as shown below:

copy code
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!");
            }
        }
    }
}
copy code

4. Double-click the item "MyWindowsService" to enter the "MyService" design interface, right-click the mouse in a blank position to pop up the context menu, and select "Add Installer", as shown in the following figure:

5. At this time, the software will generate two components, namely "serviceInstaller1" and "serviceProcessInstaller1", as shown in the following figure:

6. Click "serviceInstaller1", in the "Properties" window, change the ServiceName to MyService, the Description to my service, and the StartType to be Manual, as shown in the following figure:

7. Click "serviceProcessInstaller1" and change Account to LocalSystem (service property system level) in the "Properties" window, as shown in the following figure:

8. Right-click the project "MyWindowsService", and select the "Generate" button in the pop-up context menu, as shown in the following figure:

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

3. Create Windows Forms for installing, starting, stopping, and uninstalling services

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

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

3. Press F7 to enter the code editing interface, refer to "System.ServiceProcess" and "System.Configuration.Install", and enter the following code:

copy 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: install 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: Uninstall service
        private void button3_Click(object sender, EventArgs e)
        {
            if (this.IsServiceExisted(serviceName))
            {
                this.ServiceStop(serviceName);
                this.UninstallService(serviceFilePath);
            }
        }

        //Check if the service exists
        private bool IsServiceExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController sc in services)
            {
                if (sc.ServiceName.ToLower() == serviceName.ToLower())
                {
                    return true;
                }
            }
            return false;
        }

        //install service
        private void InstallService(string serviceFilePath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceFilePath;
                IDictionary savedState = new Hashtable();
                installer.Install(savedState);
                installer.Commit(savedState);
            }
        }

        //Uninstall the service
        private void UninstallService(string serviceFilePath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceFilePath;
                installer.Uninstall(null);
            }
        }
        // start the service
        private void ServiceStart(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Stopped)
                {
                    control.Start();
                }
            }
        }

        //Out of service
        private void ServiceStop(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Running)
                {
                    control.Stop();
                }
            }
        }
    }
}
copy code

4. For the needs of subsequent debugging services and installation and uninstallation services, reference the generated MyWindowsService.exe to this Windows form, as shown in the following figure:

5. Since you need to install the service, you need to use the Administrator permission in UAC, right-click the item "WindowsServiceClient", select "Add" -> "New Item" in the pop-up context menu, and select " Application Manifest File" and click OK, as shown in the following image:

6. Open the file and change <requestedExecutionLevel level="asInvoker" uiAccess="false" /> to <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />, as shown in the following figure:

7. After the IDE starts, the following window will pop up (some systems may not be displayed due to UAC configuration), you need to open it with administrator privileges:

8. After reopening, run the WindowsServiceClient project in the IDE;

9. Use WIN+R to open the run form, and enter services.msc in the form to open the service, as shown in the following figure:

10. Click the "Install Service" button in the form, and MyService will appear in the service, as shown in the following figure:

11. Click the "Run Service" button to start and run the service, as shown below:

12. Click the "Stop Service" button to stop the running service, as shown in the following figure:

13. Click the "Uninstall Service" button to delete the MyService service from the service.

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

 

Source code download:

 

 

 

Supplement: How to debug a service

1. To debug a service, it is actually very simple. If you need to attach the service process to the project that needs to be debugged, if you want to debug the service you just built, now set a breakpoint in the OnStop event, as shown below:

 

2. Start the "WindowsServiceClient" project and select "Attachment to Process" in the "Debug" menu (the service must be installed in advance), as shown below:

3. Find "MyWindowsService.exe" and click the "Add" button, as shown below:

4. Click the "Stop Service" button, the program will be interrupted at the place where the breakpoint is set, as shown in the following figure:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325301982&siteId=291194637