C# 使用Windows服务项目模板快速创建Windows服务程序

发布时间 2023-07-12 20:03:42作者: log9527

之前写了一篇使用Topshelf创建Windows服务程序的文章:https://www.cnblogs.com/log9527blog/p/17325795.html

还可以直接使用VS自带的Windows服务项目模板快速创建Windows服务程序

 Service1.cs里面的OnStart和OnStop方法分别代表服务开始,服务停止时执行的逻辑

 配置服务

Service1.cs的设计图中,右键-->添加安装程序

 项目多出一个ProjectInstaller.cs的文件

 点击ProjectInstaller,选中serviceProcessInstaller1,属性,将Account修改成LocalSystem

选中serviceInstaller1,属性,将StartType修改成Automatic(服务自启动),ServiceName为服务的名称,DisplayName为服务的描述

 生成项目。

安装服务

管理员身份运行cmd

cd C:\Windows\Microsoft.NET\Framework\v4.0.30319

 InstallUtil.exe D:\MyProjects\H3CDemo\WindowsService\bin\Debug\WindowsService.exe

卸载服务

管理员身份运行cmd

 
sc delete ServiceTest