安裝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("\r\n" + DateTime.Now.ToString() + "服務已啟動……", ServerLogUrl);
        }

        protected override void OnStop()
        {
            FileHelper.WriteTxt("\r\n" + DateTime.Now.ToString() + "服務已停止……", ServerLogUrl);
        }

        internal const string ServerLogUrl = "ServerLog.txt";
    }
View Code

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

 

 

 指定輸出:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM