windows服务程序
2024-08-27 07:37:56
首先创建一个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 = ;
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:\test.txt"))
{
sw.WriteLine(DateTime.Now);
} } }
}
写了一个定时器,每分钟向d盘中的text文本中写入时间
服务程序已经写好了,然后就是怎么启动
刚开始的时候建立了一个myService的启动程序,在该程序的bin\debug目录下建立一个Service的文件夹
然后右键myWindowsService程序,查看属性,将程序的输出路径指定为myService程序的bin\debug目录下的Service的文件夹中
在Service文件夹中建立两个bat文件Install.bat和Uninstall.bat,分别写入安装服务和卸载服务的命令
Install.bat中:
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe myWindowsService.exe
Net Start ServiceTest
sc config ServiceTest start= auto
Uninstall.bat中:
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.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();
if (!ServiceIsExisted(ServiceName))
MessageBox.Show("服务尚未安装成功,请确保以下三个名称一致," +
"\n1.程序的配置文件的服务名称 \n2.服务程序exe的名称 " +
"\n3.服务卸载脚本Uninstall.bat中服务程序名称 \n然后重新安装服务",
"提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
/// <summary>
/// 判断服务是否卸载成功
/// </summary>
public void CheckUninstall()
{
string ServiceName = System.Configuration.ConfigurationManager.AppSettings["ServiceName"];
Thread.Sleep();
if (ServiceIsExisted(ServiceName))
MessageBox.Show("服务尚未卸载成功,请确保以下三个名称一致," +
"\n1.程序的配置文件的服务名称 \n2.服务程序exe的名称 " +
"\n3.服务卸载脚本Uninstall.bat中服务程序名称 \n然后重新卸载服务",
"提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
}
添加配置文件,把服务名添加到配置文件中,这样修改服务名称的时候,相应的修改配置文件就行列
<appSettings>
<add key="ServiceName" value="ServiceTest"/>
</appSettings>
然后运行程序,点击安装,就能看到服务ServiceTest了,看不到可以在服务管理中看到,并启动它
注意,运行的时候要用管理员身份运行
demo 链接: http://pan.baidu.com/s/1cborHc 密码: 9h4e
最新文章
- JavaScript代码段整理笔记系列(二)
- 如何利用rem在移动端不同设备上让字体自适应大小
- HTML5的入门与深入理解
- 百度定位API报错:leaked ServiceConnection com.baidu.location.LocationClient$1@426122f0
- SQL Server 2005中的分区表(六):将已分区表转换成普通表(转)
- SQL Sever 2008 数据库文件的备份和还原
- iOS app 上架的流程与注意点
- Solr(四)Solr实现简单的类似百度搜索高亮功能-1.配置Ik分词器
- ActiveMQ (一) 初识ActiveMQ
- Mac 装Sequel pro 连接 Mysql 8.0 失败、登录不了、loading问题
- 结队第一次 plus
- 关于设计项目UI界面的软件工具
- java通过jdbc访问mysql,update数据返回值的思考
- nginx路径设置(web)
- smartpass
- Java中的浮点型(Double&;Float)计算问题
- ZOJ 3946.Highway Project(The 13th Zhejiang Provincial Collegiate Programming Contest.K) SPFA
- sql2000-text类型数据只能看到256个字节
- nginx默认的配置文件详解
- Java 07 example
热门文章
- css05文本,文字属性
- innodb的innodb_buffer_pool_size和MyISAM的key_buffer_size
- MTK Android 默认值修改笔记
- 设置Cacti图形标题能显示中文
- 关于iOS应用管理之九宫格的坐标计算以及与UIScrollView的结合
- Php 常用类
- 告诉你GetDC()没有释放造成的后果
- mobx react
- 洛谷 P1316 丢瓶盖
- Uncaught TypeError: Cannot set property &#39;innerHTML&#39; of null