zoukankan      html  css  js  c++  java
  • Windows 服务

     Windiws服务 允许用户创建可在其自身的Windows会话中长时间运行的可执行应用程序。这些服务可在计算机启动时自动重启,也可以暂停和停止,并且不显示任何用户界面面。这些功能是服务非常在计算机上使用,或者需要长时间运行的功能的情况。

    一、编程方式创建服务

    1、以编程方式创建服务,必须执行的步骤:

    • 必须将服务类设置为从 ServiceBase 继承需引入命名空间System.ServiceProcess.dll。
    • 必须为服务项目创建Main方法,该方法定义要运行的服务,并在其上调用 Run 方法。
    • 必须替代 OnStart 和 OnStop 过程,并填入希望运行的代码。
    • 添加服务应用程序,所必需的安装程序。
    • 生产解决方案。
    • 安装服务。

    ServiceBase 类的 Run 方法。 这是服务的主入口点。 

    使用 Windows 服务模板创建服务时,将在应用程序的 Main 方法中插入代码以运行该服务。 此代码如下所示:

    System.ServiceProcess.ServiceBase[] ServicesToRun;

    ServicesToRun = new System.ServiceProcess.ServiceBase[]

      { new Service1() };

    System.ServiceProcess.ServiceBase.Run(ServicesToRun);

     

    服务创建实例:

    1、新建一个 Windows 服务,并命名为"MyWindowsService"。

    2、在解决方案内,将Service1.cs改为Myservice.cs。

     

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

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.ServiceProcess;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace MyWindowsService
    {
        public partial class MyService : ServiceBase
        {
            public MyService()
            {
                InitializeComponent();
            }
    
            string filePath = @"D:MyServiceLog.txt";
    
            protected override void OnStart(string[] args)
            {
                using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        sw.WriteLine("{0},服务启动!",DateTime.Now);
                    }
                }
            }
    
            protected override void OnStop()
            {
                using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        sw.WriteLine("{0},服务停止!", DateTime.Now);
                    }
                }
            }
        }
    }

    4、点击项目“MyWindowsService”进入“MyService”设计界面,右键空白处,选中“添加安装程序”,如下图所示:

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

    6、点击“serviceInstaller1”,在“属性”窗体中将ServiceName改为"MyService",DisplayName改为"MyService我的服务", Description改为"我的服务描述", StartType保持为"Manual"。

    Manual

    该服务必须在安装后手动启动

    Automatic

    只要重启计算机,服务就将自行启动。

    Disabled

    服务无法启动。

    如下图所示:

    7、点击“serviceProcessInstaller1”,在“属性”窗体将Account改为"LocalSystem",如下图所示:

    默认情况下,服务在与登录用户不同的安全性上下文中运行。 服务在名为 LocalSystem 的默认系统帐户的上下文中运行,这样使服务拥有与用户不同的针对系统资源的访问权限。 可以更改此行为以指定应在其下运行服务的其他用户帐户。

    可以通过操作服务运行于其中的进程的 Account 属性来设置安全性上下文。 此属性允许将服务设置为以下四种帐户类型之一:

    User,该帐户会导致系统在安装服务时提示输入有效的用户名和密码,并在网络上单个用户指定的帐户的上下文中运行;

    LocalService,该帐户在用作本地计算机上的非特权用户的帐户的上下文中运行,并向任意远程服务器提供匿名凭据;

    LocalSystem,该帐户在提供广泛本地权限的帐户的上下文中运行,并向任意远程服务器提供计算机凭据;

    NetworkService,该帐户在用作本地计算机上的非特权用户的帐户的上下文中运行,并向任意远程服务器提供计算机凭据。

     

    8、右键项目“MyWindowsService”,选择并点击“生成”/“重新生成”,如下图所示:

     

    9、恭喜,Windows服务已经创建完毕。

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

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

    2、将此项目设定为"项目启动项"。在窗体内添加四个按钮,分别为安装服务、启动服务、停止服务、卸载服务,并添加服务状态文本框。如下图所示:

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

    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.Configuration.Install;
    using System.ServiceProcess;
    using System.Collections;
    
    namespace WindowsServiceClient
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            string serviceFilePath = $"{Application.StartupPath}\MyWindowsService.exe";
            string serviceName = "MyService";
    
            //判定服务是否存在
            private bool IsServiceExisted(string serviceName)
            {
                //检索本地计算机上的所有服务
                ServiceController[] services = ServiceController.GetServices();
                foreach (ServiceController item in services)
                {
                    if (item.ServiceName.ToUpper() == serviceName.ToUpper())
                    {
                        return true;
                    }
                }
    
                return false;
            }
    
            //安装服务
            private void InstallService(string serviceFilePath)
            {
                // 加载程序集,并在其中运行的所有安装程序
                using (AssemblyInstaller installer = new AssemblyInstaller())
                {
                    //获取或设置一个值,该值指示是否创建一个新 System.Configuration.Install.InstallContext 对象的程序集的安装。
                    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();
                        control.WaitForStatus(ServiceControllerStatus.Running);
                    }
                }
            }
    
            //停止服务
            private void ServiceStop(string serviceName)
            {
                using (ServiceController control = new ServiceController(serviceName))
                {
                    if (control.Status == ServiceControllerStatus.Running)
                    {
                        control.Stop();
                        control.WaitForStatus(ServiceControllerStatus.Stopped);
                    }
                }
            }
    
            //事件:安装服务
            private void btn_az_Click(object sender, EventArgs e)
            {
                if (this.IsServiceExisted(serviceName))
                {
                    this.UninstallService(serviceName);
                }
    
                this.InstallService(serviceFilePath);
                txt.Text = "服务安装成功";
    
            }
    
            //事件:启动服务
            private void btn_run_Click(object sender, EventArgs e)
            {
                if (this.IsServiceExisted(serviceName))
                {
                    this.ServiceStart(serviceName);
                    txt.Text = "服务正在运行";
                }
              
            }
    
            //事件:停止服务
            private void btn_stop_Click(object sender, EventArgs e)
            {
                if (this.IsServiceExisted(serviceName))
                {
                    this.ServiceStop(serviceName);
                    txt.Text = "服务停止";
                }
               
            }
    
            //事件:卸载服务
            private void btn_xiezai_Click(object sender, EventArgs e)
            {
                if (this.IsServiceExisted(serviceName))
                {
                    this.ServiceStop(serviceName);
                    this.UninstallService(serviceFilePath);
                    txt.Text = "服务已卸载";
                }
            }
        }
    }

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

    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.在窗体中,进行“安装服务”等操作。

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

    源代码下载:

    三、如何调试服务

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

    2、启动“WindowsServiceClient”项目,在“调试”菜单中选择“附件到进程”(服务必须事先安装),如下所示:

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

    4、点击“停止服务”按钮,程序将会在设置断点的地方中断,如下图所示:

     此文章参考:https://www.cnblogs.com/cncc/p/7170951.html  完成。

  • 相关阅读:
    python+opencv 运行环境搭建
    centos 安装 FLEXPART
    centos 安装npm node
    USACO4.3 Street Race【分析】
    USACO4.3 Letter Game【枚举·细节】
    结构体封装高精度 大整数BigInt
    POJ3585 Accumulation Degree【换根dp】
    换根dp特征总结
    HDU2196 Computer【换根dp】
    CF1187E Tree Painting【换根dp】
  • 原文地址:https://www.cnblogs.com/AndyChen2015/p/9553295.html
Copyright © 2011-2022 走看看