码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2015-06-11 00:16:51      阅读:259      评论:0      收藏:0      [点我收藏+]

标签: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
或者直接用手机扫描二维码查看更多博文:
技术分享

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

标签:windows-service   windows服务控   服务控制   

原文地址:http://blog.csdn.net/fuyifang/article/details/46448261

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!