首先创建一个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
 
 
 

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. (转)Discuz!NT图文安装教程

    不同目录下的安装方法根据目前大家对论坛的使用需求,在安装上面大致有三种情况,站点根目录下安装,站点虚拟目录下安装和站点子目录下安装. 1.根目录安装 根目录安装是最简单也是稳定系数最高的安装和使用方式 ...

  2. Android 软件盘 动态设置 layout

    总体来说分为三种方法: 在编辑框输入内容时会弹出软键盘,而手机屏幕区域有限往往会遮住输入界面,我们先看一下问题效果图: 输入用户名和密码时,系统会弹出键盘,造成系统键盘会挡住文本框的问题,如图所示: ...

  3. 解决CENTOS7虚拟机更改静态IP无法启动

    在linuxman的编辑中,未出现问题.反复的查看原因未果,后查明是虚拟机所致.1.在开启网络时,有错误提示:Restarting network (via systemctl):  Job for ...

  4. Jenkins学习之——(3)将项目发送到tomcat

    本章节将讲解如何将项目发送到tomcat,实现自动部署. 我只将一个测试的maven项目托管到github上的,不了解git获github的朋友自己百度一下,我也写了一些关于git的文章,希望大家可以 ...

  5. oracle登陆连接的问题

    一.登陆 1.使用客户端 直接在database中配置: IP:1521/orcl 其中IP为要连接的IP 其中1521为要连接的数据库的端口 其中orcl为要连接的数据库的实例名字 2.使用命令行 ...

  6. Knockoutjs官网翻译系列(三) 使用Computed Observables

    书接上回,前面谈到了在视图模型中可以定义普通的observable属性以及observableArray属性实现与UI元素的双向绑定,这一节我们继续探讨第三种可实现绑定的属性类型:computed o ...

  7. cos实现文件上传--推荐

    1.导包 2.核心类:MultipartRequest MultipartRequest是request的包装类 参数1:request 参数2:保存路径 参数3:上传文件大小,默认为1M 参数4:编 ...

  8. QT5在VS2013中找不到QtNetwork或QTcpSocket或QTcpSocket等头文件

    一.首先是要有相关的库文件 方法一:手动添加库文件Qt5Networkd.lib 对项目进行右键,找到相关的属性,然后查看Linker中input部分的红色选项中是否含有Qt5Networkd.lib ...

  9. python的hashlib模块

    # -*- coding: utf-8 -*- """python 的MD5 sha1 模块""" import hashlib #md5的 ...

  10. 《Linux内核分析》 week2作业-时间片轮转

    一.基于时间片轮转调度代码的解读 代码结构主要由三个文件组成: 1.mypcb.h 2.myinterrupt.c 3.mymain.c 1.进程控制块(mypcb.h) /* CPU-specifi ...