首先创建一个myService的窗体程序作为服务安装卸载控制器(管理员身份运行vs,windows服务的安装卸载需要管理员权限)

 

在同一个解决方案里面添加一个windows服务程序,取名myWindowsService

把程序原生的Service1.cs去掉,自己添加一个windows服务文件,命名为ServiceTest.cs ,修改program文件的
主函数入口方法
 
  1. static void Main()
  2. {
  3. ServiceBase[] ServicesToRun;
  4. ServicesToRun = new ServiceBase[]
  5. {
  6. new ServiceTest()
  7. };
  8. ServiceBase.Run(ServicesToRun);
  9. }
右键ServiceTest.cs的设计界面,添加一个安装程序
 
添加完成后会生成一个ProjectInstaller.cs文件,该文件的设计视图中有两个文件,分别是serviceProcessInstaller1和serviceInstaller1
 
选中serviceProcessInstaller1,修改其Account属性为LocalSystem,
选中serviceInstaller1,修改其StartType为Automatic,其属性ServiceName是指服务名称,也就是我们自己添加的那个服务文件ServiceTest.cs 的名称ServiceTest
 
到此,服务程序配置好了,接下来就是编写服务了
打开ServiceTest.cs文件的代码
在其中已经复写了服务的OnStart()和OnStop()方法
 
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.ServiceProcess;
  8. using System.Threading;
  9. using System.Timers;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using System.IO;
  13. namespace myWindowsService
  14. {
  15. partial class ServiceTest : ServiceBase
  16. {
  17. public ServiceTest()
  18. {
  19. InitializeComponent();
  20. }
  21.  
  22. protected override void OnStart(string[] args)
  23. {
  24. System.Timers.Timer time = new System.Timers.Timer();
  25. time.Interval = ;
  26. time.Elapsed += new ElapsedEventHandler(WriteText);
  27. time.AutoReset = true;
  28. time.Enabled = true;
  29. time.Start();
  30. }
  31.  
  32. protected override void OnStop()
  33. {
  34. // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
  35. }
  36.  
  37. private void WriteText(object source, ElapsedEventArgs es)
  38. {
  39. using (StreamWriter sw = File.AppendText(@"d:\test.txt"))
  40. {
  41. sw.WriteLine(DateTime.Now);
  42. }
  43.  
  44. }
  45.  
  46. }
  47. }
写了一个定时器,每分钟向d盘中的text文本中写入时间
 
服务程序已经写好了,然后就是怎么启动
刚开始的时候建立了一个myService的启动程序,在该程序的bin\debug目录下建立一个Service的文件夹
然后右键myWindowsService程序,查看属性,将程序的输出路径指定为myService程序的bin\debug目录下的Service的文件夹中
在Service文件夹中建立两个bat文件Install.bat和Uninstall.bat,分别写入安装服务和卸载服务的命令
Install.bat中:
  1. %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe myWindowsService.exe
  2. Net Start ServiceTest
  3. sc config ServiceTest start= auto
Uninstall.bat中:
  1. %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u myWindowsService.exe
 
myWindowsService.exe为服务程序生成的exe文件的名称,一般就是服务程序的名称
 
接下来编写myService服务控制程序
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. //using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.Diagnostics;
  11. using System.ServiceProcess;
  12. using System.Threading;
  13. using System.Configuration;
  14. namespace myService
  15. {
  16. public partial class Form1 : Form
  17. {
  18. public Form1()
  19. {
  20. InitializeComponent();
  21. }
  22.  
  23. private void btInstall_Click(object sender, EventArgs e)
  24. {
  25. string ServiceName = System.Configuration.ConfigurationManager.AppSettings["ServiceName"];
  26. string CurrentDirectory = System.Environment.CurrentDirectory;
  27. if (!ServiceIsExisted(ServiceName))
  28. {
  29. try
  30. {
  31. //新的线程,在10秒后判断服务是否存在,不存在则表示服务未安装成功
  32. //Thread check = new Thread(new ThreadStart(CheckInstall));
  33. //check.Start();
  34.  
  35. System.Environment.CurrentDirectory = CurrentDirectory + "\\Service";
  36. Process process = new Process();
  37. process.StartInfo.UseShellExecute = false;
  38. process.StartInfo.FileName = "Install.bat";
  39. process.StartInfo.CreateNoWindow = false;
  40. process.StartInfo.ErrorDialog = true;
  41. process.Start();
  42. System.Environment.CurrentDirectory = CurrentDirectory;
  43. label1.Text = ServiceName + "安装成功";
  44. }
  45. catch
  46. {
  47. System.Environment.CurrentDirectory = CurrentDirectory;
  48. }
  49. }
  50. else
  51. {
  52. label1.Text = ServiceName + "已安装";
  53. }
  54. }
  55.  
  56. private void btUninstall_Click(object sender, EventArgs e)
  57. {
  58. string ServiceName = System.Configuration.ConfigurationManager.AppSettings["ServiceName"];
  59. string CurrentDirectory = System.Environment.CurrentDirectory;
  60. if (ServiceIsExisted(ServiceName))
  61. {
  62. try
  63. {
  64. //Thread check = new Thread(new ThreadStart(CheckUninstall));
  65. //check.Start();
  66.  
  67. System.Environment.CurrentDirectory = CurrentDirectory + "\\Service";
  68. Process process = new Process();
  69. process.StartInfo.UseShellExecute = false;
  70. process.StartInfo.FileName = "Uninstall.bat";
  71. process.StartInfo.CreateNoWindow = false;
  72. process.StartInfo.ErrorDialog = true;
  73. process.Start();
  74. System.Environment.CurrentDirectory = CurrentDirectory;
  75. label1.Text = ServiceName + "卸载成功";
  76. }
  77. catch
  78. {
  79. System.Environment.CurrentDirectory = CurrentDirectory;
  80. }
  81. }
  82. else
  83. {
  84. label1.Text = ServiceName + "已卸载";
  85. }
  86. }
  87.  
  88. private void btStart_Click(object sender, EventArgs e)
  89. {
  90. string ServiceName = System.Configuration.ConfigurationManager.AppSettings["ServiceName"];
  91. try
  92. {
  93. ServiceController serviceController = new ServiceController(ServiceName);
  94. if (!serviceController.CanStop)
  95. serviceController.Start();
  96. label1.Text = ServiceName + "启动成功";
  97. }
  98. catch
  99. {
  100. label1.Text = ServiceName + "未启动";
  101. }
  102. }
  103.  
  104. private void btStop_Click(object sender, EventArgs e)
  105. {
  106. string ServiceName = System.Configuration.ConfigurationManager.AppSettings["ServiceName"];
  107. try
  108. {
  109. ServiceController serviceController = new ServiceController(ServiceName);
  110. if (serviceController.CanStop)
  111. serviceController.Stop();
  112. label1.Text = ServiceName + "停止成功";
  113. }
  114. catch
  115. {
  116. label1.Text = ServiceName + "未启动";
  117. }
  118. }
  119.  
  120. /// <summary>
  121. /// 判断服务是否存在
  122. /// </summary>
  123. /// <param name="serviceName"></param>
  124. /// <returns></returns>
  125. private bool ServiceIsExisted(string serviceName)
  126. {
  127. try
  128. {
  129. ServiceController[] services = ServiceController.GetServices();
  130. foreach (ServiceController s in services)
  131. {
  132. if (s.ServiceName == serviceName)
  133. {
  134. return true;
  135. }
  136. }
  137. return false;
  138. }
  139. catch
  140. {
  141. return false;
  142. }
  143. }
  144.  
  145. /// <summary>
  146. /// 判断服务是否安装成功
  147. /// </summary>
  148. public void CheckInstall()
  149. {
  150. string ServiceName = System.Configuration.ConfigurationManager.AppSettings["ServiceName"];
  151. Thread.Sleep();
  152. if (!ServiceIsExisted(ServiceName))
  153. MessageBox.Show("服务尚未安装成功,请确保以下三个名称一致," +
  154. "\n1.程序的配置文件的服务名称 \n2.服务程序exe的名称 " +
  155. "\n3.服务卸载脚本Uninstall.bat中服务程序名称 \n然后重新安装服务",
  156. "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
  157. }
  158. /// <summary>
  159. /// 判断服务是否卸载成功
  160. /// </summary>
  161. public void CheckUninstall()
  162. {
  163. string ServiceName = System.Configuration.ConfigurationManager.AppSettings["ServiceName"];
  164. Thread.Sleep();
  165. if (ServiceIsExisted(ServiceName))
  166. MessageBox.Show("服务尚未卸载成功,请确保以下三个名称一致," +
  167. "\n1.程序的配置文件的服务名称 \n2.服务程序exe的名称 " +
  168. "\n3.服务卸载脚本Uninstall.bat中服务程序名称 \n然后重新卸载服务",
  169. "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
  170. }
  171.  
  172. }
  173. }
添加配置文件,把服务名添加到配置文件中,这样修改服务名称的时候,相应的修改配置文件就行列
  1. <appSettings>
  2. <add key="ServiceName" value="ServiceTest"/>
  3. </appSettings>
 
然后运行程序,点击安装,就能看到服务ServiceTest了,看不到可以在服务管理中看到,并启动它
注意,运行的时候要用管理员身份运行
demo 链接: http://pan.baidu.com/s/1cborHc 密码: 9h4e
 
 
 

windows服务程序的更多相关文章

  1. WCF学习之旅—WCF服务的Windows 服务程序寄宿(十一)

    上接    WCF学习之旅—WCF服务部署到IIS7.5(九) WCF学习之旅—WCF服务部署到应用程序(十) 七 WCF服务的Windows 服务程序寄宿 这种方式的服务寄宿,和IIS一样有一个一样 ...

  2. C#写Windows Service(windows服务程序)

    背景:        要学习使用一个新东西,我们必须知道他是个什么东西.对于我们此次研究的windows服务来说,他又是个什么东西,其实也没有什么高深的了. windows service概述: 一个 ...

  3. 关于开发Windows服务程序容易搞混的地方!

    在开发Windows服务程序时,我们一般需要添加安装程序,即:serviceInstaller,里面有几个关于名称属性,你都搞明白了吗? 1.Description:表示服务说明(描述服务是干什么的) ...

  4. Windows服务程序和安装程序制作

    转:http://www.cr173.com/html/15350_1.html 本文介绍了如何用C#创建.安装.启动.监控.卸载简单的Windows Service 的内容步骤和注意事项. 一.创建 ...

  5. .net Windows服务程序和安装程序制作图解 及 VS 2010创建、安装、调试 windows服务(windows service)

    .net Windows服务程序和安装程序制作 最近项目中用到window服务程序,以前没接触过,比较陌生,花了两天的时间学习了下,写了个简单的服务,但在制作安装程序的时候,参照网上很多资料,却都制作 ...

  6. C# 编写Windows Service(windows服务程序)【转载】

    [转]http://www.cnblogs.com/bluestorm/p/3510398.html Windows Service简介: 一个Windows服务程序是在Windows操作系统下能完成 ...

  7. C# 创建、安装和卸载Windows服务程序

    1.新建一个windows服务程序. 2.点击这个服务类,从工具箱中加入一个Timer控件,右键这个Timer控件 命名为 timerOrderDeductionDetailJob,Enable设为T ...

  8. C语言编写Windows服务程序

    原文:C语言编写Windows服务程序 #include <Windows.h> #include <stdio.h> #define SLEEP_TIME 5000 // 间 ...

  9. 创建一个Windows服务程序与实现定时器效果

    1.创建一个Windows服务程序 一.   新建Window服务项目 二.   添加安装程序 三.   配置服务属性 四.   编写定时器代码 publicpartialclassService1 ...

随机推荐

  1. 异步tcp通信——APM.Core 服务端概述

    为什么使用异步 异步线程是由线程池负责管理,而多线程,我们可以自己控制,当然在多线程中我们也可以使用线程池.就拿网络扒虫而言,如果使用异步模式去实现,它使用线程池进行管理.异步操作执行时,会将操作丢给 ...

  2. NuGet学习笔记(1)——初识NuGet及快速安装使用(转)

    关于NuGet园子里已经有不少介绍及使用经验,本文仅作为自己研究学习NuGet一个记录. 初次认识NuGet是在去年把项目升级为MVC3的时候,当时看到工具菜单多一项Library Package M ...

  3. ant打包命令

    学习ant打包命令.发布到以上tomcat还未做集成部署,无法添加到jenkins中. http://blog.csdn.net/telnetor/article/details/7015935 ht ...

  4. IE下判断IE版本的语句

    <!--[if lte IE 6]> <![endif]--> IE6及其以下版本可见   <!--[if lte IE 7]> <![endif]--> ...

  5. 遍历页面上所有TextBox,并赋值为String.Empty

    //不含母板页 foreach (System.Web.UI.Control txtobj in this.Page.Controls)   {     if (txtobj.GetType().Na ...

  6. angularjs自定义日期过滤器,如:周日(前天 21:24)

    今天给大家分享一个,我在项目中自定义的一个日期过滤器.具体过滤出来的效果可参看下图: 用法: {{ time | timeFilter }} filter: App.filter('timeFilte ...

  7. QT5-控件-QScrollArea-可以用于把一个窗口分割为多个-比如根据图片大小显示滚动条

    #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QLabel> #incl ...

  8. delphi列表视图组件(TListView)使用方法|实例

    TListView 组件以多种形式显示列表的项目,如详细资料.小图标.大图标等形式表示列表中的项目.    列表视图与用TListBox 组件实现的列表框非常相似.不同的是,列表视图可以让用户选择不同 ...

  9. Ecshop布局参考图

    文章列表页: article_cat.dwt 文章内容页: article.dwt 商品品牌页: brand.dwt 所有分类页: catalog.dwt 商品列表页: category.dwt 商品 ...

  10. InnoDB概览

    InnoDB 采用了MVCC来支持高并发,并且实现了四个标准的隔离级别.其默认级别是REPEATABLE READ(可重复读) ,并且,通过间隙锁(next-key locking)策略防止幻读的出现 ...