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

在做一些计划任务时候难免用到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

或者直接用手机扫描二维码查看更多博文:

时间: 2024-08-11 07:33:33

C# 开发Windows Service程序控制功能的相关文章

如何利用mono把.net windows service程序迁移到linux上

How to migrate a .NET Windows Service application to Linux using mono? 写在最前:之所以用要把windows程序迁移到Linux上,主要是由于一些成本问题,这个就不多解释了. 如何把之前用.net写的windows服务程序迁移到linux上运行.答案是有很多种的,今天我只提一下mono(我只实验了mono,呵呵). 如何在Linux部署mono,并成功的运行.net程序,还请大家多多查询吧,我在这方面也只是搭建成功了,遇到的问

.Net 开发Windows Service

1.首先创建一个Windows Service 2.创建完成后切换到代码视图,代码中默认有OnStart和OnStop方法执行服务开启和服务停止执行的操作,下面代码是详细解释: using System; using System.IO; usingSystem.ServiceProcess; using System.Text; usingSystem.Timers; namespaceTestService { public partial class Service1 : ServiceB

VS2010 创建 windows service 程序

参考网上保护眼睛程序,自写程序如下. 1.创建一个名词为“CareEyeService”,类型为“WindowsService”的应用程序. 自动生成代码如下图: 2.修改ServiceCareEye.cs的代码 public partial class ServiceCareEye : ServiceBase { private Thread MainThread; public ServiceCareEye() { InitializeComponent(); MainThread = ne

vs2013创建、安装、调试Windows Service程序

Windows服务以服务的形式运行,有些情况下非常有用.用VS2013创建windows服务的过程如下: 创建服务. 1.文件->新建->项目->windows桌面->windows服务,修改你要的项目名称.我这不改名,仍叫WindowsService1,确定. 2.产生的项目文件结构如图所示.右侧的Program.cs文件是入口,Service1.cs是服务文件,所有的逻辑都在这.Service1.cs包含两部分,一部分是Designer,可以在这里面添加各种组件.一部分是后台文

使用Visual Studio 2008创建你的第一个Windows Mobile程序介绍

使用Visual Studio 2008创建你的第一个Windows Mobile程序介绍 Windows MobileMobileWindowsMicrosoftWinForm 介绍 Microsoft Visual Studio 2008 专业版或者更高版本提供了一个Windows Mobile程序开发环境,允许你使用本地代码(C / C++)或托管代码(C# / Visual Basic.NET)为Windows Mobile设备创建程序. 这篇文章将带你正确的安装Visual Studi

windows service in vs

用 vs2013 创建 windows service 程序 vs2015开发Windows服务 VS 2010一步步开发windows服务(windows service)

解决VS2008 开发Windows Mobile 项目生成速度慢的问题(转)

最近用VS2008开发Windows Mobile程序,使用C#..NET Compact Framework,发现项目生成速度比较慢.用VS2008打开项目后,开始一段时间生成速度还能忍受,时间一长,编译速度巨慢,最慢达到5分钟之久,实在无法忍受. 决定找出VS2008生成时,做了什么花费时间的工作.从工具à选项进入“选项”对话框 选择“MSBuild项目生成输出详细信息”为“诊断”这样编译时,会输出具体执行了那些任务,花费了多少时间. 结果发现最花费时间的是 Platform Verific

golang 开发windows应用

闲着无聊又玩go语言找虐...--用go开发windows应用程序 想要用go开发windows应用必须先要安装必要的组件: walk集成了很多windows的控件 go get github.com/lxn/walk win是go调用windowsApi的一种实现 go get github.com/lxn/win rsrc是连接walk/win和windows动态连接的工具 go get github.com/akavel/rsrc 有了这些我们就能实际的编码了 先测试一下winApi的有效

使用javascript开发windows phone应用的相关问题

1.使用angularjs和winjs时的兼容问题 1.开启scp模式 <html ng-app="app" ng-csp><!-- Enables CSP (Content Security Policy) support --> 2.使用winjs提供的垫片文件 使在winjs内无法使用innerHTML.innerText等技术的jquery.angularjs能够正常工作 <!-- 安全模式shim,为了使用angular和jquery -->