一、创建Windows Service
1、新建一个Windows Service,并将项目名称改为"MyWindowsService":
2、在解决方案中将Service1.cs改为MyService.cs
3、点击查看代码
using System; using System.IO; using System.ServiceProcess; namespace MyWindowsService { public partial class MyService : ServiceBase { string filePath = @"C:\Work\ServiceLog.txt"; public MyService() { InitializeComponent(); } protected override void OnStart(string[] args) { using (FileStream stream = new FileStream(filePath, FileMode.Append)) using (StreamWriter writer = new StreamWriter(stream)) { writer.WriteLine($"{DateTime.Now},服务启动!"); } } protected override void OnStop() { using (FileStream stream = new FileStream(filePath, FileMode.Append)) using (StreamWriter writer = new StreamWriter(stream)) { writer.WriteLine($"{DateTime.Now},服务停止!"); } } } }
4、双击项目“MyWindowsService”进入"MyService"设计界面,在空白位置右击鼠标弹出上下文菜单,选中"Add Installer"
5、生成两个组件,分别是"serviceInstaller1"和"serviceProcessInstaller1"
6、点击"serviceInstaller1",在"属性"窗体将ServiceName改为MyService,Description改为我的服务
7、点击"serviceProcessInstaller1",在"属性"窗体将Account改为LocalSystem
8、生成服务程序。
二、创建安装、启动、停止、卸载服务的窗体
1、在同一解决方案中新建一个Windows Form项目,命名为WindowsServiceClient
2、将该项目设置为启动项目,并在窗体内添加四个按钮,分别为安装服务、启动服务、停止服务及卸载服务
3、添加引用"System.Configuration.Install"及"System.ServiceProcess"
4、编辑代码
using System; using System.Collections; using System.Windows.Forms; using System.ServiceProcess; using System.Configuration.Install; namespace WindowsServiceClient { public partial class Form1 : Form { string serviceFilePath = $"{Application.StartupPath}\\MyWindowsService.exe"; string serviceName = "MyService"; public Form1() { InitializeComponent(); } private void btnInstall_Click(object sender, EventArgs e) { if (this.IsServiceExisted(serviceName)) this.UninstallService(serviceFilePath); this.InstallService(serviceFilePath); } private void btnStart_Click(object sender, EventArgs e) { if (this.IsServiceExisted(serviceName)) this.ServiceStart(serviceName); } private void btnStop_Click(object sender, EventArgs e) { if (this.IsServiceExisted(serviceName)) this.ServiceStop(serviceName); } private void btnUninstall_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(); } } } } }
5、添加调试引用,
6、由于需要安装服务,故需要使用UAC中Administrator的权限,在项目“WindowsServiceClient”添加“Application Manifest File”并单击确定
7、编辑该文件,将<requestedExecutionLevel level="asInvoker" uiAccess="false" />改为<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<?xml version="1.0" encoding="utf-8"?> <assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1"> <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <!-- UAC Manifest Options If you want to change the Windows User Account Control level replace the requestedExecutionLevel node with one of the following. <requestedExecutionLevel level="asInvoker" uiAccess="false" /> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> <requestedExecutionLevel level="highestAvailable" uiAccess="false" /> Specifying requestedExecutionLevel element will disable file and registry virtualization. Remove this element if your application requires this virtualization for backwards compatibility. --> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> </requestedPrivileges> </security> </trustInfo> <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"> <application> <!-- A list of the Windows versions that this application has been tested on and is is designed to work with. Uncomment the appropriate elements and Windows will automatically selected the most compatible environment. --> <!-- Windows Vista --> <!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />--> <!-- Windows 7 --> <!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />--> <!-- Windows 8 --> <!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />--> <!-- Windows 8.1 --> <!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />--> <!-- Windows 10 --> <!--<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />--> </application> </compatibility> <!-- Indicates that the application is DPI-aware and will not be automatically scaled by Windows at higher DPIs. Windows Presentation Foundation (WPF) applications are automatically DPI-aware and do not need to opt in. Windows Forms applications targeting .NET Framework 4.6 that opt into this setting, should also set the 'EnableWindowsFormsHighDpiAutoResizing' setting to 'true' in their app.config. --> <!-- <application xmlns="urn:schemas-microsoft-com:asm.v3"> <windowsSettings> <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware> </windowsSettings> </application> --> <!-- Enable themes for Windows common controls and dialogs (Windows XP and later) --> <!-- <dependency> <dependentAssembly> <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" /> </dependentAssembly> </dependency> --> </assembly>
标签:C#,创建,void,System,new,Windows,serviceName,installer,using From: https://www.cnblogs.com/cabinsummer/p/16730091.html