转载地址:https://www.cnblogs.com/JourneyOfFlower/p/10391633.html c#编写windows服务:https://www.cnblogs.com/knowledgesea/p/3616127.html 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
}
}
记得用管理员身份运行起来,否则会操作 失败的 未用管理员权限运行结果
管理员权限运行结果 如下 效果如下 **
C# 开发Windows服务程序并在计算机上注册服务
**
1、VS新建 Windows服务 项目
2、向服务中函数功能实现【在解决方案中 右键[Service1.cs]然后点击 查看代码 进入到代码视图】 可已看到 下面两个函数
OnStart函数在启动服务时执行,OnStop函数在停止服务时执行。在这两个函数中完成自己的代码逻辑。
3、回到 Service1.cs[设计] 设计窗口点右键选择-添加安装程序 -生成serviceInstaller1和 serviceProcessInstaller1两个组件 把serviceInstaller1的属性ServiceName改写为你的服务程序名,并把启动模 式设置为AUTOMATIC 把serviceProcessInstaller1的属性account改写为 LocalSystem
4、重新生成整个解决方案
二、注册服务
通过cmd命令安装、卸载、启动和停止Windows Service(InstallUtil.exe)
1、运行--〉cmd:打开cmd命令框
2、在命令行里定位到InstallUtil.exe所在的位置
InstallUtil.exe 默认的安装位置是在C:/Windows/Microsoft.NET/Framework/v2.0.50727里面,所以你要在cmd里通过cd定位到该位置(cd C:/Windows/Microsoft.NET/Framework/v2.0.50727)
3、操作命令:
1). 安装服务命令:在命令行里输入下面的命令:
InstallUtil.exe Path/WinServiceName.exe
其中Path表示ServiceName.exe所在的位置,回车即可
2). 启动服务命令
net start ServiceName
ServiceName是真正的Service的名称(ServiceBase.ServiceName),跟.exe的名称可能一样,也可能不一样。如果不清楚,就到已安装的服务里面找到你的服务,右键属性里面看服务名称
3). 停止服务命令
net stop ServiceName
4). 卸载服务命令:在命令行里输入下面的命令:
InstallUtil.exe /u Path/WinServiceName.exe
其中Path表示ServiceName.exe所在的位置,回车即可
三、备注
1.Service启动属性:
Manual 服务安装后,必须手动启动。
Automatic 每次计算机重新启动时,服务都会自动启动。
Disabled 服务无法启动。
2.新建的Service项目,其中各属性的含义(设计视图->右键属性):
Autolog 是否自动写入系统的日志文件
CanHandlePowerEvent 服务时候接受电源事件
CanPauseAndContinue 服务是否接受暂停或继续运行的请求
CanShutdown 服务是否在运行它的计算机关闭时收到通知,以便能够调用 OnShutDown 过程
CanStop 服务是否接受停止运行的请求
ServiceName 服务名
3. 也可以在系统服务管理器中,设置相应Service的属性或启动方式等
计算机管理 -> 服务和应用程序 -> 服务 -> ...