1,打开VS,新建一个windows服务程序。项目名称自定义,我这里用的默认名称:Service1

2,打开Service1,按F7查看代码。代码里有三个方法:public Service1()、protected override void OnStart(string[] args)、protected override void OnStop(),

分别是构造函数,服务启动方法,服务停止方法

3,定义一个timer定时器,设置一段时间自动执行:

System.Timers.Timer timer1;  //计时器

timer1 = new System.Timers.Timer();
timer1.Interval = 3000; //设置计时器事件间隔执行时间
timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
timer1.Enabled = true;

4,编写服务具体执行的业务,这里是模拟的,就只写了一个txt文档,并且把写txt文档的方法放到了定时器的自动执行方法里

/// <summary>
/// 执行的事件
/// </summary>
/// <param name="obj"></param>
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    using (FileStream stream = new FileStream(filePath, FileMode.Append))
    using (StreamWriter writer = new StreamWriter(stream))
    {
        writer.WriteLine(DateTime.Now + ",自动服务的执行。。。");
    }
}

5,编译一下,无编译错误即可。完整的代码如下:

public partial class Service1 : ServiceBase
{
System.Timers.Timer timer1; //计时器
string filePath = @"D:\MyServiceLog.txt";

public Service1()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
timer1 = new System.Timers.Timer();
timer1.Interval = 3000; //设置计时器事件间隔执行时间
timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
timer1.Enabled = true;

using (FileStream stream = new FileStream(filePath, FileMode.Append))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(DateTime.Now + ",服务启动!");
}
}

protected override void OnStop()
{
this.timer1.Enabled = false;

using (FileStream stream = new FileStream(filePath, FileMode.Append))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(DateTime.Now + ",服务停止!");
}
}

/// <summary>
/// 执行的事件
/// </summary>
/// <param name="obj"></param>
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
using (FileStream stream = new FileStream(filePath, FileMode.Append))
using (StreamWriter writer = new StreamWriter(stream))
{
writer.WriteLine(DateTime.Now + ",自动服务的执行。。。");
}
}
}

6,在解决方案里双击Service.cs,打开设计器:

在空白处右击,选择“添加安装程序”

点击之后如下

7,查看serviceInstaller1的属性,编辑它的描述信息和服务名称信息,如下:

点击 serviceProcessInstaller1 ,编辑运行次服务的账户类型属性,设置成 LocalSystem,如下:

8,服务配置完成,点击保存,重新生成。

9,下面,我们写一个Windows窗体,用于安装、运行、停止、卸载这个服务:

10,添加一个应用引用,把刚才写的服务引用到这个Windows窗体应用

11,给每个按钮添加相应的代码,完整如下:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

string serviceFilePath = System.Environment.CurrentDirectory + "\\WindowsService1.exe";
string serviceName = "TestWindowsService";

/// <summary>
/// 安装服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName))
this.UninstallService(serviceName);
this.InstallService(serviceFilePath);
}
/// <summary>
/// 启动服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName))
this.ServiceStart(serviceName);
}
/// <summary>
/// 停止服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName))
this.ServiceStop(serviceName);
}
/// <summary>
/// 卸载服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName))
{
this.ServiceStop(serviceName);
this.UninstallService(serviceFilePath);
}
}

//判断服务是否存在
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();
}
}
}

}

12,编译,运行起来,点击安装服务。然后在计算机管理里,查看所有的服务,就可以找到刚才写的服务了:

.net手动编写Windows服务的更多相关文章

  1. python实现编写windows服务

    使用python编写windows服务 最近测试服务器上经常发生磁盘空间不足,每次手动清除比较麻烦,所以写个windows服务定时清理下.中间也遇到过几个坑,一起记录下来. 1.python实现win ...

  2. C#编写windows服务

    项目要求: 数据库用有一张表,存放待下载文件的地址,服务需要轮训表将未下载的文件下载下来. 表结构如下: 过程: VS--文件-->新建项目-->windows-->windows服 ...

  3. 使用C语言编写windows服务一般框架

    原文:使用C语言编写windows服务一般框架 编写windows服务和编写windows应用程序一样,有一些回调函数必须填写且向windows 服务管理器(service manager)进行注册, ...

  4. C#编写Windows 服务

    C#编写Windows 服务 Microsoft Windows 服务(即,以前的 NT 服务)使您能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序.这些服务可以在计算机启动时 ...

  5. C# 编写windows服务及服务的安装、启动、删除、定时执行任务

    一.编写windows服务 1.VS2017  - 创建服务Myservice 2.创建好项目之后 --- >> 双击 Service1.cs  ---- >>  出现一个设计 ...

  6. c# 编写windows 服务,并制作安装包

    对服务的认识有很多个阶段. 第一阶段:当时还在用c++,知道在一个进程里while(True){},然后里面做很多很多事情,这就叫做服务了,界面可能当时还用Console控制台程序. 第二阶段:知道了 ...

  7. 手把手教用C#编写Windows服务 并控制服务 安装、启动、停止、卸载

    Windows服务 Microsoft Windows 服务(即,以前的 NT 服务)使您能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序.这些服务可以在计算机启动时自动启动, ...

  8. 第八篇--编写Windows服务

    编写service服务参考网址:https://blog.csdn.net/nodeathphoenix/article/details/24181509 vc获得显示器状态(捕获息屏.亮屏网址):h ...

  9. 编写Windows服务疑问1:操作过程

    Windows 服务开发平时不太受人关注,毕竟那是高大上的项目类型,平常需求也用不上,很多老掉牙的家伙也只知有WinForm,仍不知有WPF,更别说Windows 服务了,正如陶渊明所写的,“不知有汉 ...

随机推荐

  1. ringojs 基于jvm 的javascript 平台试用

    ringojs 是一个基于jvm 的javascript 平台,支持commonjs 模块模式 安装 下载包配置环境变量,或者使用docker,测试使用docker dockerfile deb 包安 ...

  2. vs2013突然没有代码提示功能了。

    工具->选项->文本编辑器->C++ ->高级->禁用IntelliSense设置 false 然后选确定.

  3. Git Flow分支策略

    就像代码需要代码规范一样,代码管理同样需要一个清晰的流程和规范 Vincent Driessen 同学为了解决这个问题提出了 A Successful Git Branching Model 下面是G ...

  4. 闲扯淡笔记 - Web的历史

    这里的Web指的是万维网,就是World Wide Web. 文档和静态资源 通过URL组织 Tim Berners Lee (TimBL) 于1989发明这个概念,这丫55年出生,和我父亲一般大. ...

  5. Python VIL Realse

    #!/usr/bin/python #-*- coding:utf-8 –*- import os import sys import re import shutil import xlrd imp ...

  6. java 面向对象 — 继承

    继承中的构造方法,先执行父类中的构造方法,然后执行子类中的构造方法 继承中的属性,最后执行的属性 覆盖前面的属性 因为是开辟了 两个内存空间,所以相比较是不同的. 如果想比较两个对象的值是否相同的话, ...

  7. codeforce1029B B. Creating the Contest(简单dp,简单版单调栈)

    B. Creating the Contest time limit per test 1 second memory limit per test 256 megabytes input stand ...

  8. [转][Java]自定义标签简介

    作用:自定义标签主要用于移除 jsp 页面中的 java 代码. 实现:需要完成以下两个步骤: 编写一个实现 Tag 接口的 Java 类,把页面 java 代码移到这个 java 类中.(标签处理类 ...

  9. ROS+OPENVPN配置

    环境需求:ROS版本:5.26,OPENVPN版本:OpenVPNPortable1.0.3(下载地址http://sourceforge.net/projects/ovpnp/)在WIN7 X64, ...

  10. Spring源码分析之——导入spring-framework源代码到Eclipse

    本人最近想要研究spring的源代码,但当要导入spring sub project到Eclipse里面去的时候遇到了不少麻烦(其实都怪自己想当然). 找到spring-framework的gitHu ...