1.操做系统:Windows 10 X64编程
2.开发环境:VS2017windows
3.编程语言:C#编程语言
4. .NET版本:.NET Framework 4.5编辑器
1.新建一个Windows Service,并将项目名称改成“MyWinsService”,程序保存路径本身选一个,以下图所示:ide
二、在解决方案资源管理器内将Service1.cs改成MyService1.cs后,右键“查看代码”图标按钮进入代码编辑器界面,下面直接贴代码:ui
string filePath = $"{Application.StartupPath}\\MyserviceLog.txt"; protected override void OnStart(string[] args) { using (FileStream stream = new FileStream(filePath, FileMode.Append)) using (StreamWriter writer=new StreamWriter(stream)) { writer.WriteLine(DateTime.Now +" "+"启动服务!"); } } protected override void OnStop() { using (FileStream stream = new FileStream(filePath, FileMode.Append)) using (StreamWriter writer = new StreamWriter(stream)) { writer.WriteLine(DateTime.Now + " " + "中止服务!"); } }
3.双击项目“MyWindowsService”进入“MyService”设计界面,在空白位置右击鼠标弹出上下文菜单,选中“添加安装程序”,以下图所示:spa
四、进入页面以后就会看到serviceProcessInstaller1和serviceInstaller1;操作系统
点击“serviceProcessInstaller1”,在“属性”窗体将Account改成LocalSystem(服务属性系统级别),以下图所示:设计
5.点击“serviceInstaller1”,在“属性”窗体将ServiceName改成MyService,Description改成个人服务,StartType保持为Manual,以下图所示:调试
6.鼠标右键点击项目“MyWinsService”,在弹出的上下文菜单中选择“生成”按钮,生成咱们本身的windows服务了。
3、建立安装、启动、中止、卸载服务的Windows窗体
1.咱们以winform为例子吧,建一个简单的界面,这里命名为ServiveMan,修改属性text为windows服务管理,拖入四个Button,分别命名为安装、启动、中止、卸载
2.整理了一个Windows服务管理的类,这里我采用的是单例模式,若是有不理解的,我下一篇文章就分享一下单例模式。
/// <summary> /// Windows服务管理 /// </summary> public class serviceManager { private static serviceManager mSingle = null;
// public static serviceManager GetInstance() { if (mSingle == null) mSingle = new serviceManager(); return mSingle; } //判断服务是否存在 private bool IsServiceExisted(string serviceName) { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController sc in services) { if (sc.ServiceName.ToLower() == serviceName.ToLower()) { return true; } } return false; } //安装服务 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); } } //卸载服务 private void UninstallService(string serviceFilePath) { using (AssemblyInstaller installer = new AssemblyInstaller()) { installer.UseNewContext = true; installer.Path = serviceFilePath; installer.Uninstall(null); } } //启动服务 private void ServiceStart(string serviceName) { using (ServiceController control = new ServiceController(serviceName)) { if (control.Status == ServiceControllerStatus.Stopped) { control.Start(); } } } //中止服务 private void ServiceStop(string serviceName) { using (ServiceController control = new ServiceController(serviceName)) { if (control.Status == ServiceControllerStatus.Running) { control.Stop(); } } } }
3.接下来贴,windows服务管理类的使用方法,直接看代码,代码上都有注释
public partial class Form1 : Form { public Form1() { InitializeComponent(); } string serviceFilePath = $"{Application.StartupPath}\\MyWindowsService.exe"; string serviceName = "MyService"; /// <summary> /// 事件:安装服务 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { //判断是否存在服务 - 存在则开启服务 if (serviceManager.GetInstance().IsServiceExisted(serviceName)) { try { serviceManager.GetInstance().ServiceStart(serviceName); //启动服务 } catch (Exception ex) { Console.WriteLine(ex.Message); } } serviceManager.GetInstance().InstallService(serviceFilePath);//不然安装服务 } /// <summary> /// 事件:启动Windows服务 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { //启动Windows服务前判断是否存在Windows服务 if (serviceManager.GetInstance().IsServiceExisted(serviceName)) { try { serviceManager.GetInstance().ServiceStart(serviceName);//开启Windows服务 } catch (Exception ex) { Console.WriteLine(ex.Message); } } else { //服务未安装 DialogResult dr = MessageBox.Show("该服务还没有安装,是否安装服务?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (dr == DialogResult.OK) { serviceManager.GetInstance().InstallService(serviceFilePath);//安装服务 } else { return; } } } /// <summary> /// 事件:中止Windows服务 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button3_Click(object sender, EventArgs e) { if (serviceManager.GetInstance().IsServiceExisted(serviceName)) { try { serviceManager.GetInstance().ServiceStop(serviceName);//中止Windows服务 } catch (Exception ex) { Console.WriteLine(ex.Message); } } } /// <summary> /// 事件:卸载Windows服务 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button4_Click(object sender, EventArgs e) { if (serviceManager.GetInstance().IsServiceExisted(serviceName)) { serviceManager.GetInstance().ServiceStop(serviceName);//中止Windows服务 serviceManager.GetInstance().UninstallService(serviceFilePath);//卸载Windows服务 } } }
四、为了后续调试服务及安装卸载服务的须要,将已生成的MyWinsService.exe引用到本Windows窗体,右键添加引用,选择项目添加就能够了。这里就不上图了。
5. 安装服务,须要使用UAC中Administrator的权限,鼠标右击项目,在弹出的上下文菜单中选择“添加”->“新建项”,在弹出的选择窗体中选择“应用程序清单文件”并单击肯定,以下图所示:
5.打开该文件,并将<requestedExecutionLevel level="asInvoker" uiAccess="false" />改成<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />,以下图所示:
6.整个过程完成了,如今咱们能够启动项目了,启动后可能会弹出以下所示的窗体(有的系统因UAC配置有可能不显示),须要用管理员权限打开:
7.重启项目以后就能够了。
八、使用WIN+R的方式打开运行窗体,并在窗体内输入services.msc后打开服务,就能够看到下图:
9.咱们能够经过刚刚写的开启服务来打开服务,若是服务不用了能够经过按钮直接中止或者卸载。
ok,今天关于windows服务的demo就分享到这了,若是有疑问的能够留言,讲的不对的欢迎指出!!!