zoukankan      html  css  js  c++  java
  • C#创建Windows服务

    一、创建Windows Service

      1、新建一个Windows Service,并将项目名称改为“MyWindowsService”,如下图所示:

    2、在解决方案资源管理器内将Service1.cs改为MyService1.cs后并点击“查看代码”图标按钮进入代码编辑器界面,如下图所示:

    3、在代码编辑器内如入以下代码,如下所示:

     1 using System;
     2 using System.ServiceProcess;
     3 using System.IO;
     4 using Quartz;
     5 using Quartz.Impl;
     6 using MyWindowsService.LogHelper;
     7 
     8 namespace MyWindowsService
     9 {
    10     public partial class MyService : ServiceBase
    11     {
    12         private IKnxLog Log;
    13         private IScheduler scheduler;
    14         
    15         public MyService()
    16         {
    17             InitializeComponent();
    18             Log = new Log4netProvider();
    19             ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
    20             scheduler = schedulerFactory.GetScheduler();
    21         }
    22         
    23         protected override void OnStart(string[] args)
    24         {
    25             scheduler.Start();
    26             Log.Info("Quartz服务成功启动");
    27         }
    28 
    29         protected override void OnStop()
    30         {
    31             scheduler.Shutdown();
    32             Log.Info("Quartz服务成功终止");
    33         }
    34     }
    35 }

    4、双击项目“MyWindowsService”进入“MyService”设计界面,在空白位置右击鼠标弹出上下文菜单,选中“添加安装程序”,如下图所示:  

    5、此时软件会生成两个组件,分别为“serviceInstaller1”及“serviceProcessInstaller1”,如下图所示:

    6、点击“serviceInstaller1”,在“属性”窗体将ServiceName改为MyService,Description改为我的服务,StartType保持为Manual,如下图所示:

        

    7、点击“serviceProcessInstaller1”,在“属性”窗体将Account改为LocalSystem(服务属性系统级别),如下图所示:

    8、鼠标右键点击项目“MyWindowsService”,在弹出的上下文菜单中选择“生成”按钮,如下图所示:

    9、至此,Windows服务已经创建完毕。

    二、创建安装、启动、停止、卸载服务的Windows窗体

    1、在同一个解决方案里新建一个Windows Form项目,并命名为WindowsServiceClient,如下图所示:

    2、将该项目设置为启动项目,并在窗体内添加四个按钮,分别为安装服务、启动服务、停止服务及卸载服务,如下图所示:

    3、按下F7进入代码编辑界面,引用“System.ServiceProcess”及“System.Configuration.Install”,并输入如下代码:

      1 using System;
      2 using System.Collections;
      3 using System.Windows.Forms;
      4 using System.ServiceProcess;
      5 using System.Configuration.Install;
      6 using MyWindowsService.LogHelper;
      7 using WorkJob;
      8 
      9 namespace WindowsServiceClient
     10 {
     11     public partial class Form1 : Form
     12     {
     13         private IKnxLog logger = new Log4netProvider();
     14         public Form1()
     15         {
     16             //string l4net = AppDomain.CurrentDomain.BaseDirectory + "/log4net.config";
     17             //log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(l4net));
     18             //logger.Info("窗体启动");
     19 
     20             InitializeComponent();
     21            
     22         }
     23         string serviceFilePath = $"{Application.StartupPath}\MyWindowsService.exe";
     24         string serviceName = "MyService";
     25 
     26         //事件:安装服务
     27         private void button1_Click(object sender, EventArgs e)
     28         {
     29             if (this.IsServiceExisted(serviceName)) this.UninstallService(serviceName);
     30             this.InstallService(serviceFilePath);
     31             MessageBox.Show("服务安装成功!");
     32         }
     33 
     34         //事件:启动服务
     35         private void button2_Click(object sender, EventArgs e)
     36         {
     37             if (this.IsServiceExisted(serviceName)) this.ServiceStart(serviceName);
     38             MessageBox.Show("服务启动成功!");
     39         }
     40 
     41         //事件:停止服务
     42         private void button4_Click(object sender, EventArgs e)
     43         {
     44             if (this.IsServiceExisted(serviceName)) this.ServiceStop(serviceName);
     45             MessageBox.Show("服务停止成功!");
     46         }
     47 
     48         //事件:卸载服务
     49         private void button3_Click(object sender, EventArgs e)
     50         {
     51             if (this.IsServiceExisted(serviceName))
     52             {
     53                 this.ServiceStop(serviceName);
     54                 this.UninstallService(serviceFilePath);
     55             }
     56             MessageBox.Show("服务卸载成功!");
     57         }
     58 
     59         //判断服务是否存在
     60         private bool IsServiceExisted(string serviceName)
     61         {
     62             ServiceController[] services = ServiceController.GetServices();
     63             foreach (ServiceController sc in services)
     64             {
     65                 if (sc.ServiceName.ToLower() == serviceName.ToLower())
     66                 {
     67                     return true;
     68                 }
     69             }
     70             return false;
     71         }
     72 
     73         //安装服务
     74         private void InstallService(string serviceFilePath)
     75         {
     76             using (AssemblyInstaller installer = new AssemblyInstaller())
     77             {
     78                 installer.UseNewContext = true;
     79                 installer.Path = serviceFilePath;
     80                 IDictionary savedState = new Hashtable();
     81                 installer.Install(savedState);
     82                 installer.Commit(savedState);
     83             }
     84         }
     85 
     86         //卸载服务
     87         private void UninstallService(string serviceFilePath)
     88         {
     89             using (AssemblyInstaller installer = new AssemblyInstaller())
     90             {
     91                 installer.UseNewContext = true;
     92                 installer.Path = serviceFilePath;
     93                 installer.Uninstall(null);
     94             }
     95         }
     96         //启动服务
     97         private void ServiceStart(string serviceName)
     98         {
     99             using (ServiceController control = new ServiceController(serviceName))
    100             {
    101                 if (control.Status == ServiceControllerStatus.Stopped)
    102                 {
    103                     control.Start();
    104                 }
    105             }
    106         }
    107 
    108         //停止服务
    109         private void ServiceStop(string serviceName)
    110         {
    111             using (ServiceController control = new ServiceController(serviceName))
    112             {
    113                 if (control.Status == ServiceControllerStatus.Running)
    114                 {
    115                     control.Stop();
    116                 }
    117             }
    118         }
    119 
    120         private void button5_Click(object sender, EventArgs e)
    121         {
    122             CreateJob job = new CreateJob();
    123             job.CreateData();
    124         }
    125 
    126     }
    127 }

    4、为了后续调试服务及安装卸载服务的需要,将已生成的MyWindowsService.exe引用到本Windows窗体,如下图所示:

    5、由于需要安装服务,故需要使用UAC中Administrator的权限,鼠标右击项目“WindowsServiceClient”,在弹出的上下文菜单中选择“添加”->“新建项”,在弹出的选择窗体中选择“应用程序清单文件”并单击确定,如下图所示:

    6、打开该文件,并将<requestedExecutionLevel level="asInvoker" uiAccess="false" />改为<requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />,如下图所示:

    7、IDE启动后,将会弹出如下所示的窗体(有的系统因UAC配置有可能不显示),需要用管理员权限打开:

    8、重新打开后,在IDE运行WindowsServiceClient项目;

    9、使用WIN+R的方式打开运行窗体,并在窗体内输入services.msc后打开服务,如下图所示:

    10、点击窗体内的“安装服务”按钮,将会在服务中出现MyService,如下图所示:

    11、点击“运行服务”按钮,将启动并运行服务,如下所示:

    12、点击“停止服务”按钮,将会停止运行服务,如下图所示:

    13、点击“卸载服务”按钮,将会从服务中删除MyService服务。

    14、以上启动及停止服务将会写入D:MyServiceLog.txt,内容如下所示:

    15、要调试服务,其实很简单,如需将服务附加进程到需要调试的项目里面即可,假如要调试刚才建的服务,现在OnStop事件里设置断点。

    16、找到“MyWindowsService.exe”,点击“附加”按钮,如下图所示:

    注:源代码(MyWindowsService)在GitHub和https://gitee.com/上。

  • 相关阅读:
    ATmega328P定时器详解
    成员指针与mem_fn
    引用传参与reference_wrapper
    定位new表达式与显式调用析构函数
    模板参数的“右值引用”是转发引用
    C++生成随机数
    测量C++程序运行时间
    Snmp扫描-snmpwalk、snmpcheck
    操作系统识别-python、nmap
    服务扫描-dmitry、nmap、amap和服务识别
  • 原文地址:https://www.cnblogs.com/cyit/p/12378463.html
Copyright © 2011-2022 走看看