Talk Is Cheap. Show Me More!!!😊|

Journey&Flower

园龄:7年3个月粉丝:40关注:121

手把手教用C#编写Windows服务 并控制服务 安装、启动、停止、卸载

Windows服务

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

创建Windows服务应用程序 即创建 Windows窗体应用程序 项目

 

然后再项目上添加新建项

 

选中Windows服务文件 出现设计界面后 在界面任意位置右键  添加安装程序

 

出现如下安装界面

 

选中 serviceInstaller 按 F4 可更改服务属性

Description :服务描述

DisplayName :服务显示名称

ServiceName :服务的真实名称

StartType :服务的 启动 类型 【手动启动、自动启动、禁用】

 

选中 serviceProcessInstaller 按 F4 设置服务的 登录 类型

 

在 MyService.cs 文件中写 服务启动 和 停止 分别 执行的 代码

最后在 Program Main() 方法中 写调用服务的 代码

以上操作就可以成功编写一个 Windows服务 了

 

继续,我们对 Windows 服务 进行安装

仍然创建一个 Windows 窗体应用程序 对刚创建的服务 进行操作【安装 、启动 、停止 、卸载】

 

 

using System;
using System.Collections;
using System.Configuration.Install;
using System.ServiceProcess;
using System.Windows.Forms;
 
namespace WindowsServiceInstallProgram
{
    public partial class ServicePacageInstall : Form
    {
        public ServicePacageInstall()
        {
            InitializeComponent();
        }
 
        string serviceProgramPath = Application.StartupPath + "\\MyService.exe";//安装服务路径
        string serviceName = "ownService";//安装服务名称 非 服务显示 名称
 
        /// <summary>
        /// 安装服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInstallService_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsExistsService(serviceName))
                {
                    UninstallService(serviceProgramPath);
                }
                InstallService(serviceProgramPath);
                MessageBox.Show(
                    string.Format("服务【{0}】安装成功!\r\n时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    string.Format("服务【{0}】安装失败!\r\n错误信息:【{1}】", serviceName, ex.Message),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
 
        }
 
        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLaunchService_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsExistsService(serviceName))
                {
                    LaunchService(serviceName);
                }
                MessageBox.Show(
                    string.Format("服务【{0}】成功启动!\r\n时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    string.Format("服务【{0}】启动失败!\r\n错误信息:【{1}】", serviceName, ex.Message),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }
 
        /// <summary>
        /// 停止服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStopService_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsExistsService(serviceName))
                {
                    StopService(serviceName);
                }
                MessageBox.Show(
                    string.Format("服务【{0}】成功停止!\r\n时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    string.Format("服务【{0}】停止失败!\r\n错误信息:【{1}】", serviceName, ex.Message),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }
 
        /// <summary>
        /// 卸载服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUninstallService_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsExistsService(serviceName))
                {
                    StopService(serviceName);
                    UninstallService(serviceProgramPath);
                    MessageBox.Show(
                        string.Format("服务【{0}】成功卸载!\r\n时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show(
                        string.Format("服务【{0}】不存在!\r\n时间:【{1}】", serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
                        "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    string.Format("服务【{0}】卸载失败!\r\n错误信息:【{1}】", serviceName, ex.Message),
                    "Tips:", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }
 
        #region 判断服务是否存在
        private bool IsExistsService(string serviceName)
        {
            /* 另一种方法
            得到当前计算机所有服务对象
            serviceController[] serviceControllers = ServiceController.GetServices();
            通过服务名【ServiceName】(非显示服务名DisplayServiceName) 得到服务对象①
            ServiceController serviceController = serviceControllers.SingleOrDefault(s => s.ServiceName == serviceName);
            */
            foreach (ServiceController sc in ServiceController.GetServices())
            {
                if (sc.ServiceName.ToUpper() == serviceName.ToUpper())
                {
                    return true;
                }
            }
            return false;
        }
        #endregion
 
        #region 安装服务
        private void InstallService(string serviceProgramPath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceProgramPath;
                IDictionary saveState = new Hashtable();
                installer.Install(saveState);
                installer.Commit(saveState);
            }
        }
        #endregion
 
        #region 启动服务
        private void LaunchService(string serviceName)
        {
            using (ServiceController currentService = new ServiceController(serviceName))
            {
                if (currentService.Status == ServiceControllerStatus.Stopped)
                {
                    currentService.Start();
                }
            }
        }
        #endregion
 
        #region 停止服务
        private void StopService(string serviceName)
        {
            using (ServiceController service = new ServiceController(serviceName))
            {
                if (service.Status == ServiceControllerStatus.Running)
                {
                    service.Stop();
                }
            }
        }
        #endregion
 
        #region 卸载服务
        private void UninstallService(string serviceProgramPath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = this.serviceProgramPath;
                installer.Uninstall(null);
            }
        }
        #endregion
    }
}

记得用管理员身份运行起来,否则会操作 失败的

未用管理员权限运行结果

 

 管理员权限运行结果 如下

 

效果如下

 

 

本文作者:Journey&Flower

本文链接:https://www.cnblogs.com/JourneyOfFlower/p/10391633.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Journey&Flower  阅读(2252)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 404 Not Found REOL
  2. 2 白色恋人 游鸿明
  3. 3 盛夏的果实 莫文蔚
  4. 4 以父之名 周杰伦
  5. 5 晴天 周杰伦
  6. 6 简单爱 周杰伦
  7. 7 东风破 周杰伦
  8. 8 稻香 周杰伦
  9. 9 爱在西元前 周杰伦
  10. 10 千里之外 费玉清-周杰伦
  11. 11 偏爱 张芸京
  12. 12 大海 张雨生
  13. 13 月亮惹的祸 张宇
  14. 14 雨一直下 张宇
  15. 15 过火 张信哲
  16. 16 隐形的翅膀 张韶涵
  17. 17 天下 张杰
  18. 18 当你孤单你会想起谁 张栋梁
  19. 19 清明雨上 许嵩
  20. 20 玫瑰花的葬礼 许嵩
  21. 21 断桥残雪 许嵩
  22. 22 城府 许嵩
  23. 23 等一分钟 徐誉滕
  24. 24 客官不可以 徐良_小凌
  25. 25 坏女孩 徐良_小凌
  26. 26 犯贱 徐良
  27. 27 菠萝菠萝蜜 谢娜
  28. 28 贝多芬的悲伤 萧风
  29. 29 睫毛弯弯 王心凌
  30. 30 我不是黄蓉 王蓉
  31. 31 秋天不回来 王强
  32. 32 今天你要嫁给我 陶喆,蔡依林
  33. 33 丁香花 唐磊
  34. 34 绿光 孙燕姿
  35. 35 求佛 誓言
  36. 36 十一年 邱永传
  37. 37 下辈子如果我还记得你 马郁
  38. 38 一千年以后 林俊杰
  39. 39 江南 林俊杰
  40. 40 曹操 林俊杰
  41. 41 背对背拥抱 林俊杰
  42. 42 会呼吸的痛 梁静茹
  43. 43 勇气 梁静茹
  44. 44 爱你不是两三天 梁静茹
  45. 45 红日 李克勤
  46. 46 星月神话 金莎
  47. 47 嘻唰唰 花儿乐队
  48. 48 穷开心 花儿乐队
  49. 49 六月的雨-《仙剑奇侠传》电视剧插曲 胡歌
  50. 50 一个人的寂寞两个人的错 贺一航
  51. 51 好想好想-《情深深雨濛濛》电视剧片尾曲 古巨基
  52. 52 情人 刀郎
  53. 53 冲动的惩罚 刀郎
  54. 54 西海情歌 刀郎
  55. 55 2002年的第一场雪 刀郎
  56. 56 红玫瑰 陈奕迅
  57. 57 浮夸 陈奕迅
  58. 58 爱情转移 陈奕迅
  59. 59 独家记忆 陈小春
  60. 60 记事本 陈慧琳
  61. 61 看我72变 蔡依林
  62. 62 寂寞在唱歌 阿桑
  63. 63 樱花草 Sweety
  64. 64 中国话 S.H.E
  65. 65 波斯猫 S.H.E
  66. 66 杀破狼-《仙剑奇侠传》电视剧片头曲 JS
  67. 67 Lydia F.I.R.
  68. 68 I Miss You 罗百吉_青春美少女.
过火 - 张信哲
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

作词 : 陈佳明

作曲 : 曹俊鸿

编曲 : 屠颖

是否对你承诺了太多

还是我原本给的就不够

你始终有千万种理由

我一直都跟随你的感受

让你疯 让你去放纵

以为你 有天会感动

关于流言 我装作无动于衷

直到所有的梦已破碎

才看见你的眼泪和后悔

我是多想再给你机会

多想问你究竟爱谁

既然爱 难分是非

就别逃避 勇敢面对

给了他的心

你是否能够要得回

怎么忍心怪你犯了错

是我给你自由过了火

让你更寂寞

才会陷入感情漩涡

怎么忍心让你受折磨

是我给你自由过了火

如果你想飞

伤痛我背

是否对你承诺了太多

还是我原本给的就不够

你始终有千万种理由

我一直都跟随你的感受

让你疯 让你去放纵

以为你 有天会感动

关于流言 我装作无动于衷

直到所有的梦已破碎

才看见你的眼泪和后悔

我是多想再给你机会

多想问你究竟爱谁

既然爱 难分是非

就别逃避 勇敢面对

给了他的心

你是否能够要得回

怎么忍心怪你犯了错

是我给你自由过了火

让你更寂寞

才会陷入感情漩涡

怎么忍心让你受折磨

是我给你自由过了火

如果你想飞

伤痛我背

怎么忍心怪你犯了错

是我给你自由过了火

让你更寂寞

才会陷入感情漩涡

怎么忍心让你受折磨

是我给你自由过了火

如果你想飞

伤痛我背