在网上看到一个修改程序入口的程序去把windows 服务修改成控制台的程序,然后利用控制台的程序把服务安装和管理,也想起自己原来也写了一个对windows 报务管理的程序,不过是winform的。

    界面如下(自己使用,界面比较丑陋):
     
 
首先需要添加一个帮助类:
   代码如下:
 class Windows
    {
 
        /// <summary>
        /// 检查服务存在的存在性
        /// </summary>
        /// <param name=" NameService "> 服务名 </param>
        /// <returns> 存在返回 true,否则返回 false; </returns>
        public static bool isServiceIsExisted( string NameService)
        {
            ServiceController [] services = ServiceController.GetServices ();
            foreach (ServiceController s in services )
            {
                if (s.ServiceName.ToLower () == NameService.ToLower ())
                {
                    return true ;
                }
            }
            return false ;
        }
 
        /// <summary>
        /// 安装Windows服务
        /// </summary>
        /// <param name="stateSaver"> 集合,当传递给 Install 方法时,stateSaver 参数指定的 IDictionary 应为空。</param>
        /// <param name="filepath"> 程序文件路径 </param>
        public static void InstallmyService( IDictionary stateSaverstring filepath)
        {
            try
            {
                AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller ();
                AssemblyInstaller1.UseNewContext = true ;
                AssemblyInstaller1.Path = filepath;
                stateSaver.Clear();
                AssemblyInstaller1.Install(stateSaver );
                AssemblyInstaller1.Commit(stateSaver );
                AssemblyInstaller1.Dispose();
            }
            catch (Exception exp )
            {
                MessageBox .Show(exp.Message.ToString ());
            }
        }
 
        /// <summary>
        /// 卸载Windows服务
        /// </summary>
        /// <param name="filepath"> 程序文件路径 </param>
        public static void UnInstallmyService( IDictionary stateSaver, string filepath)
        {
            try
            {
                AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller ();
                AssemblyInstaller1.UseNewContext = true ;
                AssemblyInstaller1.Path = filepath;
                AssemblyInstaller1.Uninstall(stateSaver );
                AssemblyInstaller1.Dispose();
            }
            catch (Exception exp )
            {
                MessageBox .Show(exp.Message.ToString ());
            }
        }
 
        /// <summary>
        /// 检查Windows服务是否在运行
        /// </summary>
        /// <param name="name"> 程序的服务名 </param>
        public static bool IsRunning( string name)
        {
            bool IsRun = false ;
            try
            {
                if (!isServiceIsExisted( name))
                {
                    return false ;
                }
                ServiceController sc = new ServiceController (name);
                if (sc.Status == ServiceControllerStatus.StartPending ||
                    sc.Status == ServiceControllerStatus .Running)
                {
                    IsRun = true ;
                }
                sc.Close();
            }
            catch
            {
                IsRun = false ;
            }
            return IsRun;
        }
 
        /// <summary>
        /// 启动Windows服务
        /// </summary>
        /// <param name="name"> 程序的服务名 </param>
        /// <returns> 启动成功返回 true,否则返回 false; </returns>
        public static bool StarmyService( string name)
        {
            ServiceController sc = new ServiceController (name);
            if (sc.Status == ServiceControllerStatus.Stopped || sc.Status == ServiceControllerStatus .StopPending)
            {
 
                sc.Start();
                //sc.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 3, 0));//等待3min
            }
            sc.Close();
            return true ;
        }
 
        /// <summary>
        /// 停止Windows服务
        /// </summary>
        /// <param name="name"> 程序的服务名 </param>
        /// <returns> 停止成功返回 true,否则返回 false; </returns>
        public static bool StopmyService( string name)
        {
            ServiceController sc = new ServiceController (name);
            if (sc.Status == ServiceControllerStatus.Running ||
                sc.Status == ServiceControllerStatus .StartPending )
            {
                try
                {
 
                    sc.Stop();
                    sc.WaitForStatus( ServiceControllerStatus.Stopped new TimeSpan (010));
                }
                catch (Exception exp )
                {
                    MessageBox .Show(exp.Message.ToString ());
                }
            }
            sc.Close();
            return true ;
        }
 
        /// <summary>
        /// 重启Windows服务
        /// </summary>
        /// <param name="name"> 程序的服务名 </param>
        /// <returns> 重启成功返回 true,否则返回 false; </returns>
        public static bool RefreshmyService( string name)
        {
            return StopmyService( name&& StarmyService( name);
        }
    }

下面只需要在按钮事件下面写入不同的代码就行了:

      //安装服务
        private void btnInstall_Click (object sender EventArgs e )
        {
            try
            {
                IDictionary dictionary = new Hashtable ();
                Windows .InstallmyService(dictionary ServerPath);
                if (Windows .isServiceIsExisted (ServerName))
                {
                    this .label1.Text = "服务已经安装。。" ;
                    this .btnInstall.Enabled = false ;
                    this .btnUnInstall.Enabled = true ;
                    this .btnStart.Enabled = true ;
                    this .btnStop.Enabled = false ;
                    MessageBox .Show( "服务安装成功!" );
                }
            }
            catch (Exception exp )
            {
                this .label1.Text = "服务安装失败。。" ;
                MessageBox .Show( "服务安装失败,ErrorCode:" + exp.Message );
            }
         
        }
 
       //卸载服务
        private void btnUnInstall_Click (object sender EventArgs e )
        {
            try
            {
                IDictionary dictionary = new Hashtable ();
                Windows .UnInstallmyService(dictionary ServerPath);
                if (! Windows.isServiceIsExisted (ServerName))
                {
                    this .label1.Text = "服务已经卸载。。" ;
                    this .btnInstall.Enabled = true ;
                    this .btnUnInstall.Enabled = false ;
                    this .btnStart.Enabled = false ;
                    this .btnStop.Enabled = false ;
                    MessageBox .Show( "服务卸载成功!" );
                }
            }
            catch (Exception exp )
            {
                this .label1.Text = "服务卸载失败。。" ;
                MessageBox .Show( "服务卸载失败,ErrorCode:" + exp.Message );
            }
        }
 
 
   //启动服务
        private void btnStart_Click (object sender EventArgs e )
        {
            try
            {
                if (Windows .StarmyService (ServerName))
                {
                    this .label1.Text = "服务启动中。。" ;
                    if (Windows .IsRunning( ServerName))
                    {
                        this .label1.Text = "服务正在运行。。" ;
                        this .btnInstall.Enabled = false ;
                        this .btnUnInstall.Enabled = false ;
                        this .btnStart.Enabled = false ;
                        this .btnStop.Enabled = true ;
                    }
                }
            }
            catch (Exception exp )
            {
                this .label1.Text = "服务启动失败。。" ;
                MessageBox .Show( "服务启动失败,ErrorCode:" + exp.Message );
            }
        }
 
 
   //停止服务
        private void btnStop_Click (object sender EventArgs e )
        {
            try
            {
                if (Windows .StopmyService (ServerName))
                {
                    this .label1.Text = "服务停止中。。" ;
                    if (! Windows.IsRunning (ServerName))
                    {
                        this .label1.Text = "服务已停止。。" ;
                        this .btnInstall.Enabled = false ;
                        this .btnUnInstall.Enabled = true ;
                        this .btnStart.Enabled = true ;
                        this .btnStop.Enabled = false ;
                    }
                }
            }
            catch (Exception exp )
            {
                this .label1.Text = "服务停止失败。。" ;
                MessageBox .Show( "服务停止失败,ErrorCode:" + exp.Message );
            }
        }
      
      private void InstallServices_Load (object sender EventArgs e )
        {
            ServiceController [] services = ServiceController.GetServices ();  //加载时候把系统的服务列表加载进来
            foreach (var serviceController in services )
            {
                this .cmbServiceList.Items.Add(serviceController.ServiceName );
            } 
     }
 至此所有的功能基本上都完成了,能够对你选择的服务进行安装和卸载了,其它两个按钮的事件读者可以自己加 
Demo下载:http://pan.baidu.com/s/1dDq2i2H
 

第十三篇 一个安装、管理windows服务的桌面程序的更多相关文章

  1. 【先定一个小目标】Redis 安装成windows服务-开机自启

    1.第一步安装成windows服务的,开机自启动 redis-server --service-install redis.windows.conf 2.启动\关闭 redis-server --se ...

  2. 如何创建一个标准的Windows服务

    出处:http://www.cnblogs.com/wuhuacong/archive/2009/02/11/1381428.html 如何创建一个标准的Windows服务 在很多时候,我们需要一个定 ...

  3. MongoDB安装成为Windows服务及日常使用遇到问题总结

    安装MongoDB: http://blog.csdn.net/liuzhoulong/article/details/6124566 严格按照上面的步骤,设置数据库目录,设置日志目录,安装服务.可是 ...

  4. 将 tomcat 安装成 windows 服务

    1.下载 tomcat 的windows 压缩包,一般以 .zip ,而且文件名中有 bin 的文件就是 2.解压下载的文件到某一个目录下,eg: TOMCAT_HOME 3.打开 cmd ,运行 % ...

  5. Redis 安装成windows服务- 一主二从三哨兵,sentinel安装为Windows服务

    这里只做记录说明 Redis的主从配置网上很多文章,百度一大堆,安装流程应该都可以配置通.我使用的这篇文章 https://blog.csdn.net/u010648555/article/detai ...

  6. MongoDB配置服务--MongoDB安装成为windows服务

    MongoDB安装成为windows服务 1.打开命令提示符(最好以管理员的身份打开),然后输入: mongod --logpath "D:\MongoDB\data\log\logs.tx ...

  7. 用 nssm 把 Nginx 安装成 Windows 服务方法

    总之:用 nssm 比 srvany.exe 简便多了.1. 下载nginx windows版本:http://nginx.org/ 2. 下载 nssm :http://nssm.cc/3. 安装N ...

  8. 使用instsrv.exe+srvany.exe将应用程序安装为windows服务[转]

      转自:http://qingmu.blog.51cto.com/4571483/1248649 一.什么是instsrv.exe和srvany.exe instsrv.exe.exe和srvany ...

  9. Nginx 安装成 Windows 服务

    Nginx 安装成Windows 服务方法,具体方法如下 1. 下载nginx windows版本 http://www.nginx.org 2. 下载微软的2个工具: instsrv.exe.srv ...

随机推荐

  1. 为什么32位操作系统最大支持4GB内存

    因为32位操作系统的地址空间为32位,地址总数为2^32,每个地址对应1Byte内存空间,这样,32位操作系统管理的最大内存空间限制为2^32Byte=4*1024*1024*1024Byte,即4G ...

  2. php 中 php-fpm 的重启、终止操作命令

    php-fpm没有启动nginx会报502的错误 php 5.3.3 下的php-fpm 不再支持 php-fpm 以前具有的 /usr/local/php/sbin/php-fpm (start|s ...

  3. 把记事本文件固定在Win8的开始屏幕

    1.创建该文件的桌面快捷方式: 2.将快捷方式拷贝至开始菜单目录,在开始屏幕的查看全部中可以看见该文件快捷: 3.在查看全部中右键点击该快捷,选择固定在开始屏幕:

  4. JSP 禁用脚本设置

    JSP 禁用脚本设置: web.xml: <?xml version="1.0" encoding="UTF-8"?> <web-app xm ...

  5. 在MyEclipse 2014中给Spket增加ExtJS提示

    参考:http://wenku.baidu.com/link?url=BT2U6Z-HktQJQYpz3Jp88pJSp4lU-lXkvCqpdeaa9a-BVdOgMGK1vj486-32YC4Gq ...

  6. java操作redis redis连接池

    redis作为缓存型数据库,越来越受到大家的欢迎,这里简单介绍一下java如何操作redis. 1.java连接redis java通过需要jedis的jar包获取Jedis连接. jedis-2.8 ...

  7. JS与浏览器的几个兼容性问题

    第一个:有的浏览器不支持getElementsByClassName(),所以需要写一个function()来得到需要标签的class,然后进行class的增加.删除等操作. 第二个:在需要得到特定标 ...

  8. KB奇遇记(6):搞笑的ERP项目团队

    早在我们来之前,KB公司这边就已经组建了ERP项目组了,当时IT就只有一个人,属网管出身.而关键用户分两种类型:专职关键用户和兼职关键用户.专职关键用户组织结构上已经调动到信息部,常驻在项目组里工作, ...

  9. C#进阶系列——使用Advanced Installer制作IIS安装包(一:配置IIS和Web.config)

    前言:大过年的,写篇文章不容易,还是给自己点个赞~~年前找了下.net安装包的制作方法,发现Visual Studio自带的制作工具使用起来非常麻烦,需要单独下载安装包,并且什么激活认证等等屁事相当麻 ...

  10. C++ 头文件系列(iterator)

    简介 该头文件围绕迭代器展开,定义了一系列与迭代器有关的概念,但最最最重要的一点就是----它和其它容器一起实现了C++容器的Iterator设计模式. Iterators are a general ...