1.创建 windows服务 项目   文件 -> 新建项目 -> 已安装的模板 -> Visual C# -> windows ,在右侧窗口选择"windows 服务"

2.系统已经为我们建立了一个 Service1.cs 组件,测试时我们就用它了.  如果要新件的话,右键项目 -> 添加 -> 新建项 -> windows 服务。

3.在 Service1.cs 上 ,按 F7 (右键查看代码),打开代码页。加入我们测试用的代码。   注意:下面的几个方法中的 str 变量,为了我们一会儿调试时设置断点用的!

using System;
 using System.Diagnostics;
 using System.ServiceProcess;

 namespace WindowsService1
 {
  public partial class Service1 : ServiceBase
  {
   public Service1()
   {
    InitializeComponent();
    InitService();
   }

   /// <summary>
   /// 初始化服务参数
   /// </summary>
   private void InitService()
   {
    base.AutoLog = false;
    base.CanShutdown = true;
    base.CanStop = true;
    base.CanPauseAndContinue = true;
    base.ServiceName = "Service1";  //这个名字很重要,设置不一致会产生 1083 错误哦(在文章最后会说到这个问题)!
   }
   protected override void OnStart(string[] args)
   {
    string str ="服务开启";
   }

   protected override void OnStop()
   {
    string str ="服务停止";
   }
   protected override void OnContinue()
   {
    string str ="服务继续运行";
    base.OnContinue();
   }
   protected override void OnPause()
   {
    string str ="服务暂停";
    base.OnPause();
   }
  }
 }
View Code

相关文章: