安裝winform程式時自動安裝windows服務

來源:互聯網
上載者:User

標籤:sse   else   void   sem   nsa   技術   .com   cep   rtm   

項目中遇到一個需求:安裝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打包項目中添加自訂動作:

 

 

 指定輸出:

然後產生打包項目就可以了

安裝winform程式時自動安裝windows服務

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.