• 使用winform程序控制window服务的操作


    继上篇

    c#之添加window服务(定时任务) 

    基础之上,

    这篇文章主要讲述,使用winform程序来控制window服务的安装,启动,停止,卸载等操作

    1.在同一个解决方案添加winform项目,如图

    2.在winform设计器中添加按钮

    修改按钮名称依次为:安装服务、启动服务、停止服务、卸载服务

    3.向winform项目中添加引用:System.Configuration.Install 和 System.ServiceProcess 两个程序集(其中涉及window服务的一些操作)

     4.把之前创建的window服务也引入winform中

    5.编写代码

     public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            //安装及卸载路径
            string serviceFilePath = $"{Application.StartupPath}\WindowService_HelloWorld.exe";
            //服务名称
            string serviceName = "MyService";
            
            /// <summary>
            /// 事件:安装服务
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void button1_Click(object sender, EventArgs e)
            {
                if (IsServiceExisted(serviceName)) this.UninstallService(serviceName);
                this.InstallService(serviceFilePath);
            }
    
            /// <summary>
            /// 事件:启动服务
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void button2_Click(object sender, EventArgs e)
            {
                if (IsServiceExisted(serviceName)) this.ServiceStart(serviceName);
            }
    
            /// <summary>
            /// 停止服务
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void button3_Click(object sender, EventArgs e)
            {
                if (IsServiceExisted(serviceName)) this.ServiceStop(serviceName);
            }
    
    
            /// <summary>
            /// 卸载服务
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void button4_Click(object sender, EventArgs e)
            {
                if (IsServiceExisted(serviceName))
                {
                    this.ServiceStop(serviceName);
                    this.UninstallService(serviceFilePath);
                }
            }
    
            /// <summary>
            /// 判断服务是否存在
            /// </summary>
            /// <param name="serviceName"></param>
            /// <returns></returns>
            private bool IsServiceExisted(string serviceName)
            {
                ServiceController[] services = ServiceController.GetServices();
                foreach(ServiceController sc in services)
                {
                    if (sc.ServiceName.ToLower() == serviceName.ToLower())
                    {
                        return true;
                    }
                }
                return false;
            }
    
            /// <summary>
            /// 安装服务
            /// </summary>
            /// <param name="serviceFilePath"></param>
            private void InstallService(string serviceFilePath)
            {
                using(AssemblyInstaller installer=new AssemblyInstaller())
                {
                    installer.UseNewContext = true;
                    installer.Path = serviceFilePath;
                    IDictionary saveState = new Hashtable();
                    installer.Install(saveState);
                    installer.Commit(saveState);
                }
            }
    
            /// <summary>
            /// 卸载服务
            /// </summary>
            /// <param name="serviceFilePath"></param>
            private void UninstallService(string serviceFilePath)
            {
                using(AssemblyInstaller installer=new AssemblyInstaller())
                {
                    installer.UseNewContext = true;
                    installer.Path = serviceFilePath;
                    installer.Uninstall(null);
                }
            }
    
            /// <summary>
            /// 启动服务
            /// </summary>
            /// <param name="serviceName"></param>
            private void ServiceStart(string serviceName)
            {
                using(ServiceController controller=new ServiceController(serviceName))
                {
                    if (controller.Status == ServiceControllerStatus.Stopped)
                    {
                        controller.Start();
                    }
                }
            }
    
            /// <summary>
            /// 停止服务
            /// </summary>
            /// <param name="serviceName"></param>
            private void ServiceStop(string serviceName)
            {
                using(ServiceController controller=new ServiceController(serviceName))
                {
                    if (controller.Status == ServiceControllerStatus.Running)
                    {
                        controller.Stop();
                    }
                }
            }
    
        }

    结构如下:

     6.在项目winform中,右击项目,添加->新建项,在弹出的菜单中选择 应用程序清单文件,如图

     7.打开该文件,并将<requestedExecutionLevel level="asInvoker" uiAccess="false" />改为<requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />,如下图所示:

     8.重新生成解决方案,并运行(winform自己不知道自己是谁)

    点击安装,打开window服务管理器,发现MyService安装上了,后续几个按钮依次实验,正常

    另外还有一些调试技巧,这里就不多说了

    给出参考网址:

    https://www.cnblogs.com/cncc/p/7170951.html

    https://docs.microsoft.com/en-us/dotnet/framework/windows-services/walkthrough-creating-a-windows-service-application-in-the-component-designer

  • 相关阅读:
    匿名,排序,过滤,映射,递归函数
    内置函数图
    for(var i in items) 和 for(var i;i<items.length;i++) 区别
    js中var、let、const的区别 (待总结)
    eclipse拉取git项目 Read timed out after 30,000 ms
    eclispe git config配置文件配置远程仓库
    git pull出错:cannot pull into a repository with state: merging_resolved"
    HttpClient之用CloseableHttpClient发送post请求
    注意设置httpclient连接数
    This compilation unit is not on the build path of java project (此编译单元不在java项目的生成路径上)
  • 原文地址:https://www.cnblogs.com/Vincent-yuan/p/10859867.html
Copyright © 2020-2023  润新知