Windows服务

Microsoft Windows 服务(即,以前的 NT 服务)使您能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序。这些服务可以在计算机启动时自动启动,可以暂停和重新启动而且不显示任何用户界面。这种服务非常适合在服务器上使用,或任何时候,为了不影响在同一台计算机上工作的其他用户,需要长时间运行功能时使用。还可以在不同于登录用户的特定用户帐户或默认计算机帐户的安全上下文中运行服务。

创建Windows服务应用程序 即创建 Windows窗体应用程序 项目

然后再项目上添加新建项

选中Windows服务文件 出现设计界面后 在界面任意位置右键  添加安装程序

出现如下安装界面

选中 serviceInstaller 按 F4 可更改服务属性

Description :服务描述

DisplayName :服务显示名称

ServiceName :服务的真实名称

StartType :服务的 启动 类型 【手动启动、自动启动、禁用】

选中 serviceProcessInstaller 按 F4 设置服务的 登录 类型

在 MyService.cs 文件中写 服务启动 和 停止 分别 执行的 代码

最后在 Program Main() 方法中 写调用服务的 代码

以上操作就可以成功编写一个 Windows服务 了

继续,我们对 Windows 服务 进行安装

仍然创建一个 Windows 窗体应用程序 对刚创建的服务 进行操作【安装 、启动 、停止 、卸载】

using System;
using System.Collections;
using System.Configuration.Install;
using System.ServiceProcess;
using System.Windows.Forms; namespace WindowsServiceInstallProgram
{
public partial class ServicePacageInstall : Form
{
public ServicePacageInstall()
{
InitializeComponent();
} string serviceProgramPath = Application.StartupPath + "\\MyService.exe";//安装服务路径
string serviceName = "ownService";//安装服务名称 非 服务显示 名称 /// <summary>
/// 安装服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnInstallService_Click(object sender, EventArgs e)
{
try
{
if (IsExistsService(serviceName))
{
UninstallService(serviceProgramPath);
}
InstallService(serviceProgramPath);
MessageBox.Show(
string.Format("服务【{0}】安装成功!\r\n时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
"Tips:", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
catch (Exception ex)
{
MessageBox.Show(
string.Format("服务【{0}】安装失败!\r\n错误信息:【{1}】", serviceName, ex.Message),
"Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
} } /// <summary>
/// 启动服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLaunchService_Click(object sender, EventArgs e)
{
try
{
if (IsExistsService(serviceName))
{
LaunchService(serviceName);
}
MessageBox.Show(
string.Format("服务【{0}】成功启动!\r\n时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
"Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(
string.Format("服务【{0}】启动失败!\r\n错误信息:【{1}】", serviceName, ex.Message),
"Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
} /// <summary>
/// 停止服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnStopService_Click(object sender, EventArgs e)
{
try
{
if (IsExistsService(serviceName))
{
StopService(serviceName);
}
MessageBox.Show(
string.Format("服务【{0}】成功停止!\r\n时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
"Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(
string.Format("服务【{0}】停止失败!\r\n错误信息:【{1}】", serviceName, ex.Message),
"Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
} /// <summary>
/// 卸载服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnUninstallService_Click(object sender, EventArgs e)
{
try
{
if (IsExistsService(serviceName))
{
StopService(serviceName);
UninstallService(serviceProgramPath);
MessageBox.Show(
string.Format("服务【{0}】成功卸载!\r\n时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
"Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(
string.Format("服务【{0}】不存在!\r\n时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
"Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(
string.Format("服务【{0}】卸载失败!\r\n错误信息:【{1}】", serviceName, ex.Message),
"Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
} #region 判断服务是否存在
private bool IsExistsService(string serviceName)
{
/* 另一种方法
得到当前计算机所有服务对象
serviceController[] serviceControllers = ServiceController.GetServices();
通过服务名【ServiceName】(非显示服务名DisplayServiceName) 得到服务对象①
ServiceController serviceController = serviceControllers.SingleOrDefault(s => s.ServiceName == serviceName);
*/
foreach (ServiceController sc in ServiceController.GetServices())
{
if (sc.ServiceName.ToUpper() == serviceName.ToUpper())
{
return true;
}
}
return false;
}
#endregion #region 安装服务
private void InstallService(string serviceProgramPath)
{
using (AssemblyInstaller installer = new AssemblyInstaller())
{
installer.UseNewContext = true;
installer.Path = serviceProgramPath;
IDictionary saveState = new Hashtable();
installer.Install(saveState);
installer.Commit(saveState);
}
}
#endregion #region 启动服务
private void LaunchService(string serviceName)
{
using (ServiceController currentService = new ServiceController(serviceName))
{
if (currentService.Status == ServiceControllerStatus.Stopped)
{
currentService.Start();
}
}
}
#endregion #region 停止服务
private void StopService(string serviceName)
{
using (ServiceController service = new ServiceController(serviceName))
{
if (service.Status == ServiceControllerStatus.Running)
{
service.Stop();
}
}
}
#endregion #region 卸载服务
private void UninstallService(string serviceProgramPath)
{
using (AssemblyInstaller installer = new AssemblyInstaller())
{
installer.UseNewContext = true;
installer.Path = this.serviceProgramPath;
installer.Uninstall(null);
}
}
#endregion
}
}

记得用管理员身份运行起来,否则会操作 失败的

未用管理员权限运行结果

管理员权限运行结果 如下

效果如下

最新文章

  1. python 基础之数据类型
  2. 敏捷开发与jira
  3. Python几种主流框架
  4. IDEA之web项目(maven项目)创建
  5. Android init.rc执行顺序
  6. 每天一个linux命令---kill
  7. 简单制作 OS X Yosemite 10.10 正式版U盘USB启动安装盘方法教程
  8. 可变参数列表---以dbg()为例
  9. activity 的返回按钮
  10. SoftLAyer VPN
  11. 更换Winform 皮肤(下)----完全GDI+绘制
  12. Filter 解决web网页跳转乱码
  13. Y2 MyBatis(二)
  14. DevOps之五 Tomcat的安装与配置
  15. IDEA访问不到SpringBoot项目webapp下的内容
  16. MySQL--pymysql模块
  17. Docker Swarm 服务版本更新与回滚
  18. python代码格式检查工具部署pre_commit
  19. maven依赖有一个步长原则 如果a 对 b和c都有依赖 如果b的步长近则使用b的
  20. [Unity基础]RenderTexture

热门文章

  1. os.environ模块
  2. IDEA--IDEA debug断点调试技巧
  3. OpenJudge 2755:神奇的口袋
  4. linux_shell程序快速入门
  5. 解决计算精度问题:BigDecimal
  6. ES(ElasticSearch)文档的表现形式以及增删改查
  7. 链表习题(8)-寻找单链表中数据域大小为k的结点,并与前一结点交换,如果前一结点存在的情况下
  8. laravel中一些非常常用的php artisan命令
  9. 数据分析——Pandas的用法(Series,DataFrame)
  10. gorm 处理时间戳