Windows Service 学习系列(一):建立简单的Windows service

时间:2022-04-17 00:16:54

参考:https://www.cnblogs.com/cncc/p/7170951.html

一、开发环境

  操作系统:Windows 7 X64

  开发环境:VS2017

  编程语言:C#

  .NET版本:.NET Framework 4.6.1

  目标平台:Any CUP

二、创建Windows Service

1、新建一个Windows Service,并将项目名称改为“WindowsService1”,如下图所示:

Windows Service 学习系列(一):建立简单的Windows service

2、进入“Service1”设计界面,在空白位置右击鼠标弹出上下文菜单,选中“添加安装程序”,如下图所示:

Windows Service 学习系列(一):建立简单的Windows service

3、此时软件会生成两个组件,分别为“serviceInstaller1”及“serviceProcessInstaller1”,如下图所示:

Windows Service 学习系列(一):建立简单的Windows service

4、设置“serviceInstaller1”及“serviceProcessInstaller1”的属性

Windows Service 学习系列(一):建立简单的Windows service

Windows Service 学习系列(一):建立简单的Windows service

5、至此,Windows服务已经创建完毕。

三、创建安装、启动、停止、卸载服务的Windows窗体

1、在同一个解决方案里新建一个Windows Form项目,并命名为WindowsFormsApp1,如下图所示:

Windows Service 学习系列(一):建立简单的Windows service

2、将该项目设置为启动项目,并在窗体内添加四个按钮,分别为安装服务、启动服务、停止服务及卸载服务,如下图所示:

Windows Service 学习系列(一):建立简单的Windows service

3、按下F7进入代码编辑界面,引用“System.ServiceProcess”及“System.Configuration.Install”,并输入如下代码:

using System;
using System.Collections;
using System.Configuration.Install;
using System.ServiceProcess;
using System.Windows.Forms; namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string serviceFilePath = $"{Application.StartupPath}\\WindowsService1.exe";
string serviceName = "Service1"; /// <summary>
/// 安装服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName))
{
this.UninstallService(serviceFilePath);
}
this.InstallService(serviceFilePath);
} /// <summary>
/// 启动服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName))
{
this.ServiceStart(serviceName);
}
}
/// <summary>
/// 停止服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName))
{
this.ServiceStop(serviceName);
}
}
/// <summary>
/// 卸载服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName))
{
this.ServiceStop(serviceName);
this.UninstallService(serviceFilePath);
}
} #region 方法
/// <summary>
/// 判断服务是否存在
/// </summary>
/// <param name="serviceName"></param>
/// <returns></returns>
private bool IsServiceExisted(string serviceName)
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController sc in services)
{
if (sc.ServiceName.ToLower() == serviceName.ToLower())
{
return true;
}
}
return false;
} /// <summary>
/// 安装服务
/// </summary>
/// <param name="serviceFilePath"></param>
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);
}
} /// <summary>
/// 卸载服务
/// </summary>
/// <param name="serviceFilePath"></param>
private void UninstallService(string serviceFilePath)
{
using (AssemblyInstaller installer = new AssemblyInstaller())
{
installer.UseNewContext = true;
installer.Path = serviceFilePath;
installer.Uninstall(null);
}
}
/// <summary>
/// 启动服务
/// </summary>
/// <param name="serviceName"></param>
private void ServiceStart(string serviceName)
{
using (ServiceController control = new ServiceController(serviceName))
{
if (control.Status == ServiceControllerStatus.Stopped)
{
control.Start();
}
}
} /// <summary>
/// 停止服务
/// </summary>
/// <param name="serviceName"></param>
private void ServiceStop(string serviceName)
{
using (ServiceController control = new ServiceController(serviceName))
{
if (control.Status == ServiceControllerStatus.Running)
{
control.Stop();
}
}
}
#endregion
}
}

4、为了后续调试服务及安装卸载服务的需要,将已生成的MyWindowsService.exe引用到本Windows窗体,如下图所示:

Windows Service 学习系列(一):建立简单的Windows service

5、由于需要安装服务,故需要使用UAC中Administrator的权限,鼠标右击项目“WindowsServiceClient”,在弹出的上下文菜单中选择“添加”->“新建项”,在弹出的选择窗体中选择“应用程序清单文件”并单击确定,如下图所示:

Windows Service 学习系列(一):建立简单的Windows service

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

Windows Service 学习系列(一):建立简单的Windows service