温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#创建Windows服务的实现方法

发布时间:2020-10-14 18:27:25 来源:脚本之家 阅读:159 作者:键盘演绎青春 栏目:编程语言

Microsoft Windows 服务能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序。这些服务可以在计算机启动时自动启动,可以暂停和重新启动而且不显示任何用户界面。这使服务非常适合在服务器上使用,或任何时候,为了不影响在同一台计算机上工作的其他用户,需要长时间运行功能时使用。还可以在不同于登录用户的特定用户帐户或默认计算机帐户的安全上下文中运行服务。

一、创建Windows 服务

1.新建一个Windows 服务,并将项目名称改为“WindowsServiceDemo”,如下图所示:

C#创建Windows服务的实现方法

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

C#创建Windows服务的实现方法

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

using System;
using System.ServiceProcess;
using System.IO;

namespace WindowsServiceDemo
{
  public partial class MyService : ServiceBase
  {
    public MyService()
    {
      InitializeComponent();
    }

    string filePath = @"D:\MyServiceLog.txt";

    protected override void OnStart(string[] args)
    {
      using (FileStream stream = new FileStream(filePath, FileMode.Append))
      using (StreamWriter writer = new StreamWriter(stream))
      {
        writer.WriteLine($"{DateTime.Now},服务启动!");
      }
    }

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

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

C#创建Windows服务的实现方法

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

C#创建Windows服务的实现方法

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

C#创建Windows服务的实现方法

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

C#创建Windows服务的实现方法

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

C#创建Windows服务的实现方法

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

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

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

C#创建Windows服务的实现方法

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

C#创建Windows服务的实现方法

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

C#创建Windows服务的实现方法

using System;
using System.Collections;
using System.Windows.Forms;
using System.ServiceProcess;
using System.Configuration.Install;

namespace WindowsServiceClient
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }
    string serviceFilePath = $"{Application.StartupPath}\\WindowsServiceDemo.exe";
    string serviceName = "MyService";

    //事件:安装服务
    private void button1_Click(object sender, EventArgs e)
    {
      if (this.IsServiceExisted(serviceName)) this.UninstallService(serviceName);
      this.InstallService(serviceFilePath);
    }

    //事件:启动服务
    private void button2_Click(object sender, EventArgs e)
    {
      if (this.IsServiceExisted(serviceName)) this.ServiceStart(serviceName);
    }

    //事件:停止服务
    private void button3_Click(object sender, EventArgs e)
    {
      if (this.IsServiceExisted(serviceName)) this.ServiceStop(serviceName);
    }

    //事件:卸载服务
    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();
        }
      }
    } 
  }
}

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

C#创建Windows服务的实现方法

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

C#创建Windows服务的实现方法

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

C#创建Windows服务的实现方法

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

C#创建Windows服务的实现方法

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

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

C#创建Windows服务的实现方法

10.运行程序"Form1"点击窗体内的“安装服务”按钮,将会在服务中出现MyService,如下图所示:

C#创建Windows服务的实现方法

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

C#创建Windows服务的实现方法

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

C#创建Windows服务的实现方法

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

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

C#创建Windows服务的实现方法

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI