C# 开发Windows Service程序控制功能

简介: 在做一些计划任务时候难免用到Windows Service服务程序,而这个是没有操作界面的,每次启动、重启、关闭都需要服务界面找到服务进行操作,对普通的人来说是非常麻烦的,所以有时候就需要通过应用程序来控制Windows 服务,这里把之前写到的一个服务控制类贴出来。

在做一些计划任务时候难免用到Windows Service服务程序,而这个是没有操作界面的,每次启动、重启、关闭都需要服务界面找到服务进行操作,对普通的人来说是非常麻烦的,所以有时候就需要通过应用程序来控制Windows 服务,这里把之前写到的一个服务控制类贴出来。

服务设置截图

C# Windows 服务控制类代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
using System.Threading;

namespace Tools.App
{
    public class ServiceHelper
    {
        /// <summary>  
        /// Restart windows service  
        /// </summary>  
        /// <param name="serviceName">the windows service display name</param>  
        /// <returns> If the restart successfully return true else return false</returns>  
        public static bool RestartWindowsService(string serviceName)
        {
            bool bResult = false;
            try
            {
                try
                {
                    StopWindowsService(serviceName);
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    StartWindowsService(serviceName);
                    Thread.Sleep(1000);
                    StopWindowsService(serviceName);
                    Thread.Sleep(1000);
                    Console.WriteLine(ex.Message);
                }
                try
                {
                    StartWindowsService(serviceName);
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    StopWindowsService(serviceName);
                    Thread.Sleep(1000);
                    StartWindowsService(serviceName);
                    Thread.Sleep(1000);
                    Console.WriteLine(ex.Message);
                }
                bResult = true;
            }
            catch (Exception ex)
            {
                bResult = false;
                throw ex;
            }
            return bResult;
        }

        /// <summary>  
        /// Start windows service  
        /// </summary>  
        /// <param name="serviceName">the windows service display name</param>  
        /// <returns>If the start successfully return true else return false</returns>  
        public static bool StopWindowsService(string serviceName)
        {
            ServiceController[] scs = ServiceController.GetServices();
            bool bResult = false;
            foreach (ServiceController sc in scs)
            {
                if (sc.ServiceName == serviceName)
                {
                    try
                    {
                        sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(1000 * 30));
                        sc.Stop();
                        bResult = true;
                    }
                    catch (Exception ex)
                    {
                        bResult = false;
                        throw ex;
                    }
                }
            }
            return bResult;
        }

        /// <summary>  
        /// Stop windows service  
        /// </summary>  
        /// <param name="serviceName">the windows service display name</param>  
        /// <returns>If the stop successfully return true else return false</returns>  
        public static bool StartWindowsService(string serviceName)
        {
            ServiceController[] scs = ServiceController.GetServices();
            bool bResult = false;
            foreach (ServiceController sc in scs)
            {
                if (sc.ServiceName == serviceName)
                {
                    try
                    {
                        sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(1000 * 30));
                        sc.Start();
                        bResult = true;
                    }
                    catch (Exception ex)
                    {
                        bResult = false;
                        throw ex;
                    }
                }
            }
            return bResult;
        }


        public static bool ServiceIsExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController s in services)
            {
                if (s.ServiceName == serviceName)
                {
                    return true;
                }
            }
            return false;
        }
    }
}

窗体按钮事件调用代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Windows.Forms;

namespace Tools.App
{
    public partial class ServiceForm : Form
    {
        public ServiceForm()
        {
            InitializeComponent();
        }


        /// <summary>
        /// 加载判断服务是否存在
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ServiceForm_Load(object sender, EventArgs e)
        {

            if (ServiceHelper.ServiceIsExisted("TaskTimer"))
            {
                ServiceController service = new ServiceController("TaskTimer");
                if (service.Status != ServiceControllerStatus.Stopped && service.Status != ServiceControllerStatus.StopPending)
                {
                    this.btnStart.Enabled = false;
                    this.button2.Enabled = true;
                }
                else
                {
                    this.btnStart.Enabled = true;
                    this.button2.Enabled = false;
                }

            }
        }

        /// <summary>
        /// 启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            ServiceHelper.StartWindowsService("TaskTimer");
            this.btnStart.Enabled = false;
            this.button2.Enabled = true;
            MessageBox.Show("启动成功", "提示");
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            ServiceHelper.StopWindowsService("TaskTimer");
            this.btnStart.Enabled = true;
            this.button2.Enabled = false;
            MessageBox.Show("关闭成功", "提示");
        }

        private void btnIsExisted_Click(object sender, EventArgs e)
        {
            bool bl = ServiceHelper.ServiceIsExisted("TaskTimer");
            if (bl)
            {
                MessageBox.Show("TaskTimer 存在!", "提示");
            }
            else
            {
                MessageBox.Show("TaskTimer 不存在!", "提示");
            }
        }
    }
}

希望以上分享对初学朋友有些帮助,谢谢!
更多关注付义方技术博客:http://blog.csdn.net/fuyifang
或者直接用手机扫描二维码查看更多博文:
付义方CSDN博客二维码

目录
相关文章
|
15天前
|
存储 文字识别 C#
.NET开源免费、功能强大的 Windows 截图录屏神器
今天大姚给大家分享一款.NET开源免费(基于GPL3.0开源协议)、功能强大、简洁灵活的 Windows 截图、录屏、Gif动图制作神器:ShareX。
|
1月前
|
Windows
Windows 命令提示符(CMD)操作(七):扩展命令和功能
Windows 命令提示符(CMD)操作(七):扩展命令和功能
50 0
|
2月前
|
Java Unix 应用服务中间件
使用java service wrapper把windows flume做成服务
使用java service wrapper把windows flume做成服务
|
3月前
|
监控 API 开发工具
Baumer工业相机堡盟工业相机如何通过NEOAPI SDK获取每张图像的微秒时间和FrameID功能(C#)
Baumer工业相机堡盟工业相机如何通过NEOAPI SDK获取每张图像的微秒时间和FrameID功能(C#)
48 0
|
3月前
|
数据采集 API 开发工具
Baumer工业相机堡盟工业相机如何通过NEOAPI SDK使用ForceIP强制修改网口IP功能(C#)
Baumer工业相机堡盟工业相机如何通过NEOAPI SDK使用ForceIP强制修改网口IP功能(C#)
26 0
|
3月前
|
编解码 监控 开发工具
Baumer工业相机堡盟工业相机如何通过NEOAPI SDK使用Binning像素合并功能(C#)
Baumer工业相机堡盟工业相机如何通过NEOAPI SDK使用Binning像素合并功能(C#)
17 0
|
1天前
|
C#
【C#】 如何实现文本框历史记录提示功能
【C#】 如何实现文本框历史记录提示功能
11 0
|
8天前
|
开发框架 前端开发 JavaScript
采用C#.Net +JavaScript 开发的云LIS系统源码 二级医院应用案例有演示
技术架构:Asp.NET CORE 3.1 MVC + SQLserver + Redis等 开发语言:C# 6.0、JavaScript 前端框架:JQuery、EasyUI、Bootstrap 后端框架:MVC、SQLSugar等 数 据 库:SQLserver 2012
|
1月前
|
Windows
windows server 2019 安装NET Framework 3.5失败,提示:“安装一个或多个角色、角色服务或功能失败” 解决方案
windows server 2019 安装NET Framework 3.5失败,提示:“安装一个或多个角色、角色服务或功能失败” 解决方案
105 0
|
1月前
|
数据可视化 数据库 C++
Qt 5.14.2揭秘高效开发:如何用VS2022快速部署Qt 5.14.2,打造无与伦比的Windows应用
Qt 5.14.2揭秘高效开发:如何用VS2022快速部署Qt 5.14.2,打造无与伦比的Windows应用