C#编写Windows服务程序

来源:互联网 发布:mac win10 鼠标滚轮 编辑:程序博客网 时间:2024/05/16 07:39
网上的资料要么太乱太复杂,要么存在错误,要么写的不清不楚,要么各种判断都不处理直接报错没有抛出异常。我这里整理了一下,不会太深入。
1、首先建立一个windows服务项目
C编写Windows服务程序 - Marknoon - KeepItSimpleStupid
 取名为WindowsServiceTest
在项目中存在一个Service1.cs文件,将其重命名为ServiceTest.cs
打开Service1.cs进入设计界面,然后右键如下:
C编写Windows服务程序 - Marknoon - KeepItSimpleStupid
 选择“添加安装程序”,项目中会出现一个新文件ProjectInstaller.cs,打开这个文件,出现如下这个界面:
C编写Windows服务程序 - Marknoon - KeepItSimpleStupid
 我改变了位置,不要在意这些细节。右键点击serviceInstaller1选择属性,将ServiceName改成ServiceTest。
右键点击serviceProcessInstaller1选择属性,将Account改成LocalSystem。

2、打开ServiceTest.cs文件,进入代码编写界面(右键查看代码)。
添加如下代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsServiceTest
{
public partial class ServiceTest : ServiceBase
{
public ServiceTest()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\log.txt", true))
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Start.");
}
}

protected override void OnStop()
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\log.txt", true))
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Stop.");
}
}
}
}

这里只增加了两条语句,服务开启时或停止时在C盘下的文件log.txt里写下一些记录。

3、创建安装脚本
在项目中添加两个文件:Install.bat文件

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe WindowsServiceTest.exe
Net Start ServiceTest
sc config ServiceTest start= auto//自动启动服务

上面第一句话就是从目录中寻找那个exe文件,如果你是64位,就将Framework改成Framework64,

最好先去那个目录查找一下路径是否正确,是否存在那个exe文件。后面跟着的WindowsServiceTest.exe

就是你这个项目的可执行文件名。第二行的ServiceTest就是服务名,当你服务安装成功后可以在我的电脑->

管理->服务里看到了。

Uninstall.bat文件

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u WindowsServiceTest.exe


4、此时,服务这边已经写好了,接下来我们需要一个界面来操作。
在当前解决方案下新建一个WPF项目,叫WindowsServiceTestUI,添加对System.ServiceProcess的引用。

在WindowsServiceTestUI的bin\Debug目录下建立Service目录。

WindowsServiceTest的生成目录设置为上面创建的Service目录,并将Install.batUninstall.bat文件也放入该目录,如下:

右键WindowsServiceTest项目,属性,生成,将输出路径改为上面所说的Service的目录,如图:

C编写Windows服务程序 - Marknoon - KeepItSimpleStupid
 
5、接下来在WindowsServiceTestUI项目的设计界面增加6个按钮
C编写Windows服务程序 - Marknoon - KeepItSimpleStupid
 双击进入代码编写页面,代码如下
Install: 安装服务

private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
ServiceController serviceController = new ServiceController("ServiceTest");
ServiceControllerStatus status = serviceController.Status;
serviceController.Dispose();
MessageBox.Show("指定的服务已存在,不需要重复安装!");
}
catch (Exception ext)
{
string CurrentDirectory = System.Environment.CurrentDirectory;
System.Environment.CurrentDirectory = CurrentDirectory + "\\Service";
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = "Install.bat";
process.StartInfo.CreateNoWindow = true;
process.Start();
System.Environment.CurrentDirectory = CurrentDirectory;
MessageBox.Show("服务安装成功!");
}
}

Uninstall: 卸载服务

private void Button_Click_1(object sender, RoutedEventArgs e)
{
try
{
ServiceController serviceController = new ServiceController("ServiceTest");
ServiceControllerStatus status = serviceController.Status;
serviceController.Dispose();
string CurrentDirectory = System.Environment.CurrentDirectory;
System.Environment.CurrentDirectory = CurrentDirectory + "\\Service";
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = "Uninstall.bat";
process.StartInfo.CreateNoWindow = true;
process.Start();
System.Environment.CurrentDirectory = CurrentDirectory;
MessageBox.Show("服务已卸载!");
}
catch (Exception ext)
{
MessageBox.Show("无法完成卸载;" + ext.Message);
}
}

Start: 启动服务

private void Button_Click_2(object sender, RoutedEventArgs e)
{
try
{
ServiceController serviceController = new ServiceController("ServiceTest");
if (serviceController.Status == ServiceControllerStatus.Running)
{
MessageBox.Show("服务已经在启动!");
}
else
{
serviceController.Start();
MessageBox.Show("服务启动成功!");
}
}
catch (Exception ext)
{
MessageBox.Show("服务尚未安装;" + ext.Message);
}
}

Stop: 停止服务

private void Button_Click_3(object sender, RoutedEventArgs e)
{
try
{
ServiceController serviceController = new ServiceController("ServiceTest");
if (serviceController.CanStop && serviceController.Status != ServiceControllerStatus.Stopped)
{
serviceController.Stop();
}
MessageBox.Show("服务已停止!");
}
catch (Exception ext)
{
MessageBox.Show("服务尚未安装;" + ext.Message);
}
}

Pause: 暂停服务

private void Button_Click_4(object sender, RoutedEventArgs e)
{
try
{
ServiceController serviceController = new ServiceController("ServiceTest");
if (serviceController.CanPauseAndContinue)
{
if (serviceController.Status == ServiceControllerStatus.Running)
{
serviceController.Pause();
MessageBox.Show("服务已暂停!");
}
else if (serviceController.Status == ServiceControllerStatus.Paused)
{
serviceController.Continue();
MessageBox.Show("服务已启动!");
}
}
else
{
MessageBox.Show("无法暂停服务!");
}
}
catch (Exception ext)
{
MessageBox.Show("服务尚未安装" + ext.Message);
}
}

Look: 查看当前服务状态

private void Button_Click_5(object sender, RoutedEventArgs e)
{
try
{
ServiceController serviceController = new ServiceController("ServiceTest");
ServiceControllerStatus status = serviceController.Status;
serviceController.Dispose();
MessageBox.Show("当前服务状态:" + status);
}
catch (Exception ext)
{
MessageBox.Show("服务尚未安装;" + ext.Message);
}
}


6、将WindowsServiceTestUI项目设为启动项目,按F5调试即可出现操作界面。
C编写Windows服务程序 - Marknoon - KeepItSimpleStupid

PS:可能存在权限问题导致功能失效,原因是bat文件需要管理员权限,此时重新打开VS2012需要以管理员身份运行VS2012,然后再操作即可。

That's all. Thank you!
0 0
原创粉丝点击