首先创建一个myService的窗体程序作为服务安装卸载控制器(管理员身份运行vs,windows服务的安装卸载需要管理员权限)
在同一个解决方案里面添加一个windows服务程序,取名myWindowsService
把程序原生的Service1.cs去掉,自己添加一个windows服务文件,命名为ServiceTest.cs ,修改program文件的
主函数入口方法
static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new ServiceTest() }; ServiceBase.Run(ServicesToRun); }
右键ServiceTest.cs的设计界面,添加一个安装程序
添加完成后会生成一个ProjectInstaller.cs文件,该文件的设计视图中有两个文件,分别是serviceProcessInstaller1和serviceInstaller1
选中serviceProcessInstaller1,修改其Account属性为LocalSystem,
选中serviceInstaller1,修改其StartType为Automatic,其属性ServiceName是指服务名称,也就是我们自己添加的那个服务文件ServiceTest.cs 的名称ServiceTest
到此,服务程序配置好了,接下来就是编写服务了
打开ServiceTest.cs文件的代码
在其中已经复写了服务的OnStart()和OnStop()方法
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Threading; using System.Timers; using System.Text; using System.Threading.Tasks; using System.IO; namespace myWindowsService { partial class ServiceTest : ServiceBase { public ServiceTest() { InitializeComponent(); } protected override void OnStart(string[] args) { System.Timers.Timer time = new System.Timers.Timer(); time.Interval = 60000; time.Elapsed += new ElapsedEventHandler(WriteText); time.AutoReset = true; time.Enabled = true; time.Start(); } protected override void OnStop() { // TODO: 在此处添加代码以执行停止服务所需的关闭操作。 } private void WriteText(object source, ElapsedEventArgs es) { using (StreamWriter sw = File.AppendText(@"d: est.txt")) { sw.WriteLine(DateTime.Now); } } } }
写了一个定时器,每分钟向d盘中的text文本中写入时间
服务程序已经写好了,然后就是怎么启动
刚开始的时候建立了一个myService的启动程序,在该程序的bindebug目录下建立一个Service的文件夹
然后右键myWindowsService程序,查看属性,将程序的输出路径指定为myService程序的bindebug目录下的Service的文件夹中
在Service文件夹中建立两个bat文件Install.bat和Uninstall.bat,分别写入安装服务和卸载服务的命令
Install.bat中:
%SystemRoot%Microsoft.NETFrameworkv4.0.30319installutil.exe myWindowsService.exe Net Start ServiceTest sc config ServiceTest start= auto
Uninstall.bat中:
%SystemRoot%Microsoft.NETFrameworkv4.0.30319installutil.exe /u myWindowsService.exe
myWindowsService.exe为服务程序生成的exe文件的名称,一般就是服务程序的名称
接下来编写myService服务控制程序
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; //using System.Threading.Tasks; using System.Windows.Forms; using System.Diagnostics; using System.ServiceProcess; using System.Threading; using System.Configuration; namespace myService { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btInstall_Click(object sender, EventArgs e) { string ServiceName = System.Configuration.ConfigurationManager.AppSettings["ServiceName"]; string CurrentDirectory = System.Environment.CurrentDirectory; if (!ServiceIsExisted(ServiceName)) { try { //新的线程,在10秒后判断服务是否存在,不存在则表示服务未安装成功 //Thread check = new Thread(new ThreadStart(CheckInstall)); //check.Start(); System.Environment.CurrentDirectory = CurrentDirectory + "\Service"; Process process = new Process(); process.StartInfo.UseShellExecute = false; process.StartInfo.FileName = "Install.bat"; process.StartInfo.CreateNoWindow = false; process.StartInfo.ErrorDialog = true; process.Start(); System.Environment.CurrentDirectory = CurrentDirectory; label1.Text = ServiceName + "安装成功"; } catch { System.Environment.CurrentDirectory = CurrentDirectory; } } else { label1.Text = ServiceName + "已安装"; } } private void btUninstall_Click(object sender, EventArgs e) { string ServiceName = System.Configuration.ConfigurationManager.AppSettings["ServiceName"]; string CurrentDirectory = System.Environment.CurrentDirectory; if (ServiceIsExisted(ServiceName)) { try { //Thread check = new Thread(new ThreadStart(CheckUninstall)); //check.Start(); System.Environment.CurrentDirectory = CurrentDirectory + "\Service"; Process process = new Process(); process.StartInfo.UseShellExecute = false; process.StartInfo.FileName = "Uninstall.bat"; process.StartInfo.CreateNoWindow = false; process.StartInfo.ErrorDialog = true; process.Start(); System.Environment.CurrentDirectory = CurrentDirectory; label1.Text = ServiceName + "卸载成功"; } catch { System.Environment.CurrentDirectory = CurrentDirectory; } } else { label1.Text = ServiceName + "已卸载"; } } private void btStart_Click(object sender, EventArgs e) { string ServiceName = System.Configuration.ConfigurationManager.AppSettings["ServiceName"]; try { ServiceController serviceController = new ServiceController(ServiceName); if (!serviceController.CanStop) serviceController.Start(); label1.Text = ServiceName + "启动成功"; } catch { label1.Text = ServiceName + "未启动"; } } private void btStop_Click(object sender, EventArgs e) { string ServiceName = System.Configuration.ConfigurationManager.AppSettings["ServiceName"]; try { ServiceController serviceController = new ServiceController(ServiceName); if (serviceController.CanStop) serviceController.Stop(); label1.Text = ServiceName + "停止成功"; } catch { label1.Text = ServiceName + "未启动"; } } /// <summary> /// 判断服务是否存在 /// </summary> /// <param name="serviceName"></param> /// <returns></returns> private bool ServiceIsExisted(string serviceName) { try { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController s in services) { if (s.ServiceName == serviceName) { return true; } } return false; } catch { return false; } } /// <summary> /// 判断服务是否安装成功 /// </summary> public void CheckInstall() { string ServiceName = System.Configuration.ConfigurationManager.AppSettings["ServiceName"]; Thread.Sleep(10000); if (!ServiceIsExisted(ServiceName)) MessageBox.Show("服务尚未安装成功,请确保以下三个名称一致," + " 1.程序的配置文件的服务名称 2.服务程序exe的名称 " + " 3.服务卸载脚本Uninstall.bat中服务程序名称 然后重新安装服务", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); } /// <summary> /// 判断服务是否卸载成功 /// </summary> public void CheckUninstall() { string ServiceName = System.Configuration.ConfigurationManager.AppSettings["ServiceName"]; Thread.Sleep(10000); if (ServiceIsExisted(ServiceName)) MessageBox.Show("服务尚未卸载成功,请确保以下三个名称一致," + " 1.程序的配置文件的服务名称 2.服务程序exe的名称 " + " 3.服务卸载脚本Uninstall.bat中服务程序名称 然后重新卸载服务", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
添加配置文件,把服务名添加到配置文件中,这样修改服务名称的时候,相应的修改配置文件就行列
<appSettings> <add key="ServiceName" value="ServiceTest"/> </appSettings>
然后运行程序,点击安装,就能看到服务ServiceTest了,看不到可以在服务管理中看到,并启动它
注意,运行的时候要用管理员身份运行
demo 链接: http://pan.baidu.com/s/1cborHc 密码: 9h4e