创建安装、启动、停止、卸载服务的Windows窗体
1、在同一个解决方案里新建一个Windows Form项目,并命名为WindowsServiceClient,如下图所示:

3、按下F7进入代码编辑黢茕茚痔界面,引用“System.ServiceProcess”及“System.Configuration.Install”,并输入如下代码: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"; //事件:安装服务 private void button1_Click(object sender, EventArgs e) { if (this.IsServiceExisted(serviceName)) this.UninstallService(serviceName); this.InstallService(serviceFilePath); } //事件:启动服务 private void button2_Click(object sender, EventArgs e) { if (this.IsServiceExisted(serviceName)) this.ServiceStart(serviceName); } //事件:停止服务 private void button4_Click(object sender, EventArgs e) { if (this.IsServiceExisted(serviceName)) this.ServiceStop(serviceName); } //事件:卸载服务 private void button3_Click(object sender, EventArgs e) { if (this.IsServiceExisted(serviceName)) { this.ServiceStop(serviceName); this.UninstallService(serviceFilePath); } } //判断服务是否存在 private bool IsServiceExisted(string serviceName) { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController sc in services) { if (sc.ServiceName.ToLower() == serviceName.ToLower()) { return true; } } return false; } //安装服务 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); } } //卸载服务 private void UninstallService(string serviceFilePath) { using (AssemblyInstaller installer = new AssemblyInstaller()) { installer.UseNewContext = true; installer.Path = serviceFilePath; installer.Uninstall(null); } } //启动服务 private void ServiceStart(string serviceName) { using (ServiceController control = new ServiceController(serviceName)) { if (control.Status == ServiceControllerStatus.Stopped) { control.Start(); } } } //停止服务 private void ServiceStop(string serviceName) { using (ServiceController control = new ServiceController(serviceName)) { if (control.Status == ServiceControllerStatus.Running) { control.Stop(); } } } }}
4、为了后续调试服务及安装卸载服务的需要,将已生成的MyWindowsService.exe引用到本Windows窗体,如下图所示:

6、打开该文件,并将<requeste蟠校盯昂dExecutionLevel level="asInvoker" uiAccess="false" />改为<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />,如下图所示:

8、重新打开后,在IDE运行WindowsServiceClient项目;使用WIN+R的方式打开运行窗体,并在窗体内输入services.msc后打开服务,如下图所示:

10、点击“运行服务”按钮,将启动并运行服务,如下所示:

12、点击“卸载服务”按钮,将会从服务中删除MyService服务。以上启动及停止服务将会写入D:\MyServiceLog.txt,内容如下所示:
