• 安装winform程序时自动安装windows服务


    项目中遇到一个需求:安装winform程序时自动安装windows服务,且windows服务运行时反过来检测winform程序是否启动。如果没有则启动。

    经过一番查阅已在win10下实现并运行正常。在此记录便于以后查看

    实现思路:利用打包插件VS installer 有一个自定义操作,可以指定安装完成后运行的程序集,并在程序集中默认启动一个windows服务安装类

    实现步骤:1.在winform程序所在解决方案中,添加一个vs installer打包项目, vs installer的使用不再累述,请百度。。

         2. 创建一个类库项目作自定义操作用

         3. 这是服务安装帮助类 用于安装或删除服务

     public class ServiceHelper
        {
            /// <summary>
            /// 服务是否存在
            /// </summary>
            /// <param name="serviceName"></param>
            /// <returns></returns>
            public static bool IsServiceExisted(string serviceName)
            {
                ServiceController[] services = ServiceController.GetServices();
                foreach (ServiceController s in services)
                {
                    if (s.ServiceName == serviceName)
                    {
                        return true;
                    }
                }
                return false;
            }
    
            /// <summary>
            /// 启动服务
            /// </summary>
            /// <param name="serviceName"></param>
            public static void StartService(string serviceName)
            {
                if (IsServiceExisted(serviceName))
                {
                    ServiceController service = new ServiceController(serviceName);
                    if (service.Status != ServiceControllerStatus.Running &&
                        service.Status != ServiceControllerStatus.StartPending)
                    {
                        service.Start();
                        for (int i = 0; i < 60; i++)
                        {
                            service.Refresh();
                            System.Threading.Thread.Sleep(1000);
                            if (service.Status == ServiceControllerStatus.Running)
                            {
                                break;
                            }
                            if (i == 59)
                            {
                                throw new Exception("Start Service Error:" + serviceName);
                            }
                        }
                    }
                }
            }
    
            /// <summary>
            /// 获取服务状态
            /// </summary>
            /// <param name="serviceName"></param>
            /// <returns></returns>
            public static ServiceControllerStatus GetServiceStatus(string serviceName)
            {
                ServiceController service = new ServiceController(serviceName);
                return service.Status;
            }
    
            /// <summary>
            /// 配置服务
            /// </summary>
            /// <param name="serviceName"></param>
            /// <param name="install"></param>
            public static void ConfigService(string serviceName, bool install)
            {
                TransactedInstaller ti = new TransactedInstaller();
                ti.Installers.Add(new ServiceProcessInstaller
                {
                    Account = ServiceAccount.LocalSystem, 
                });
                ti.Installers.Add(new ServiceInstaller
                {
                    DisplayName = serviceName,
                    ServiceName = serviceName,
                    Description = "定时启动医掌管服务端",
                    ServicesDependedOn = new string[] { },//前置服务 ServicesDependedOn = new string[] { "MSSQLSERVER" }
                    StartType = ServiceStartMode.Automatic//运行方式
                });
                ti.Context = new InstallContext();
                string strPath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                ti.Context.Parameters["assemblypath"] = strPath + "\" + "RestartService.exe"; //Assembly.GetEntryAssembly().Location
                if (install)
                {
                    ti.Install(new Hashtable());
                }
                else
                {
                    ti.Uninstall(null);
                }
            }
        }
    View Code
    View Code

    4.添加windows服务的类库

    /// 定时任务客户端
        /// </summary>
        public class AutoTaskClient : Registry
        {
            public AutoTaskClient()
            {
                Schedule<StartupWinfrom>().ToRunNow().AndEvery(1).Minutes();
            }
            public void Start()
            {
                JobManager.Initialize(this);
            }
        }
    
        /// <summary>
        /// 定时启动winform程序
        /// </summary>
        public class StartupWinfrom : IJob
        {
            public void Execute()
            {
                Process proc = Process.GetProcessesByName("xxxServer").FirstOrDefault();
                if (proc == null)
                {
                    string path = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\xxxServer.exe";
                    CjwdevHelper.StartProcess(path);
                }
            }
        }
    View Code
     public partial class Service1 : ServiceBase
        {
            public Service1()
            {
                InitializeComponent();
            }
    
            protected override void OnStart(string[] args)
            {
                new AutoTaskClient().Start();
                FileHelper.WriteTxt("
    " + DateTime.Now.ToString() + "服务已启动……", ServerLogUrl);
            }
    
            protected override void OnStop()
            {
                FileHelper.WriteTxt("
    " + DateTime.Now.ToString() + "服务已停止……", ServerLogUrl);
            }
    
            internal const string ServerLogUrl = "ServerLog.txt";
        }
    View Code

    5.最后在installer打包项目中添加自定义操作:

     

     指定输出:

    然后生成打包项目就可以了

  • 相关阅读:
    string_view暴力串串题
    字符串hash暴力串串题
    C++刷leetcode几点注意事项
    微软面试算法题(整理)
    Leetcode中的Dijkstra算法
    gdb在线调试多线程程序
    2022亚马逊校园招聘软件开发实习提前批面试题
    python模块tqdm(进度条)的使用
    解决 Failed while installing Dynamic Web Module
    最新eclipse从零开始建立SpringMVC项目(详细过程)
  • 原文地址:https://www.cnblogs.com/hepeng/p/9418648.html
Copyright © 2020-2023  润新知