您好,登錄后才能下訂單哦!
這篇文章主要介紹“C#如何啟動Windows服務的窗體程序”,在日常操作中,相信很多人在C#如何啟動Windows服務的窗體程序問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”C#如何啟動Windows服務的窗體程序”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
C#啟動Windows服務的窗體程序的由來:最近應客戶的要求,做了一個定時監控WINDOWS服務的程序,要做到隨機啟動,定時監控指定的服務,如果沒有開啟則開啟,由于時間倉促,沒有經過長時間的服務器端運行,現將思路及代碼公布,以后有改進會及時更新:
一、C#啟動Windows服務的窗體程序思路:
本程序的核心在于隨機啟動和WINDOWS服務上,對于隨機啟動,引入Microsoft.Win32命名空間,利用RegistryKey類即可完成對注冊表的增、刪、改等操作;對于WINDOWS服務,引入System.ServiceProcess命名空間,利用ServiceController類即可完成對系統服務的啟動、停止、查詢等操作。改日就測試程序的穩定性及資源消耗率等指標。
二、C#啟動Windows服務的窗體程序代碼如下,這里程序默認為開啟MSSQLSERVER服務,并添加了托盤區圖標,可以在啟動時或啟動后最小化到托盤區:
using System; //C#啟動Windows服務的窗體程序using System.Drawing; using System.Collections; using System.ComponentModel; using System.windows.Forms; using System.Data; using System.ServiceProcess; using System.IO; using Microsoft.Win32; namespace WatchService { /// ﹤summary﹥ /// Form1 的摘要說明,C#啟動Windows服務的窗體程序 /// ﹤/summary﹥ public class WatchService : System.windows.Forms.Form { private System.windows.Forms.Button btn_startWatch; private System.windows.Forms.Button btn_stopWatch; private System.windows.Forms.Button btn_startReg; private System.windows.Forms.Button btn_stopReg; private System.windows.Forms.Label lbl_appStatus; private System.windows.Forms.TextBox tbx_serviceName; private System.windows.Forms.Button btn_Exit; private System.windows.Forms.TextBox tbx_interval; private System.windows.Forms.Timer timer1; private System.windows.Forms.NotifyIcon notifyIcon1; private System.ComponentModel.IContainer components; public WatchService() { // C#啟動Windows服務的窗體程序 // windows 窗體設計器支持所必需的 // InitializeComponent(); // // TODO: 在 InitializeComponent //調用后添加任何構造函數代碼 // } /// ﹤summary﹥///C#啟動Windows服務的窗體程序 /// 清理所有正在使用的資源。 /// ﹤/summary﹥ protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region windows 窗體設計器生成的代碼 /// ﹤summary﹥ /// 設計器支持所需的方法 - 不要使用代碼編輯器修改 /// 此方法的內容。 /// ﹤/summary﹥ private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(WatchService)); this.btn_startWatch = new System.windows.Forms.Button(); this.btn_stopWatch = new System.windows.Forms.Button(); this.btn_startReg = new System.windows.Forms.Button(); this.btn_stopReg = new System.windows.Forms.Button(); this.lbl_appStatus = new System.windows.Forms.Label(); this.tbx_serviceName = new System.windows.Forms.TextBox(); this.btn_Exit = new System.windows.Forms.Button(); this.tbx_interval = new System.windows.Forms.TextBox(); this.timer1 = new System.windows.Forms.Timer(this.components); this.notifyIcon1 = new System.windows.Forms.NotifyIcon(this.components); this.SuspendLayout(); // // btn_startWatch // C#啟動Windows服務的窗體程序this.btn_startWatch.Location = new System.Drawing.Point(112, 8); this.btn_startWatch.Name = "btn_startWatch"; this.btn_startWatch.Size = new System.Drawing.Size(64, 23); this.btn_startWatch.TabIndex = 0; this.btn_startWatch.Text = "開始監控"; this.btn_startWatch.Click += new System.EventHandler(this.btn_startWatch_Click); // // btn_stopWatch // this.btn_stopWatch.Location = new System.Drawing.Point(184, 8); this.btn_stopWatch.Name = "btn_stopWatch"; this.btn_stopWatch.Size = new System.Drawing.Size(64, 23); this.btn_stopWatch.TabIndex = 1; this.btn_stopWatch.Text = "停止監控"; // // btn_startReg // C#啟動Windows服務的窗體程序this.btn_startReg.Location = new System.Drawing.Point(112, 40); this.btn_startReg.Name = "btn_startReg"; this.btn_startReg.Size = new System.Drawing.Size(88, 24); this.btn_startReg.TabIndex = 2; this.btn_startReg.Text = "開啟隨機啟動"; this.btn_startReg.Click += new System.EventHandler(this.btn_startReg_Click); // // btn_stopReg // this.btn_stopReg.Location = new System.Drawing.Point(232, 40); this.btn_stopReg.Name = "btn_stopReg"; this.btn_stopReg.Size = new System.Drawing.Size(88, 24); this.btn_stopReg.TabIndex = 3; this.btn_stopReg.Text = "關閉隨機啟動"; this.btn_stopReg.Click += new System.EventHandler(this.btn_stopReg_Click); // // lbl_appStatus // C#啟動Windows服務的窗體程序this.lbl_appStatus.ForeColor = System.Drawing.Color.Red; this.lbl_appStatus.Location = new System.Drawing.Point(16, 72); this.lbl_appStatus.Name = "lbl_appStatus"; this.lbl_appStatus.Size = new System.Drawing.Size(304, 23); this.lbl_appStatus.TabIndex = 4; this.lbl_appStatus.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // tbx_serviceName // this.tbx_serviceName.BorderStyle = System.windows.Forms.BorderStyle.FixedSingle; this.tbx_serviceName.ForeColor = System.Drawing.Color.Red; this.tbx_serviceName.Location = new System.Drawing.Point(8, 8); this.tbx_serviceName.Name = "tbx_serviceName"; this.tbx_serviceName.TabIndex = 5; this.tbx_serviceName.Text = "輸入服務名"; this.tbx_serviceName.MouseDown += new System.windows.Forms.MouseEventHandler( this.tbx_serviceName_MouseDown); // // btn_Exit // this.btn_Exit.Location = new System.Drawing.Point(256, 8); this.btn_Exit.Name = "btn_Exit"; this.btn_Exit.Size = new System.Drawing.Size(64, 23); this.btn_Exit.TabIndex = 6; this.btn_Exit.Text = "退出程序"; this.btn_Exit.Click += new System.EventHandler(this.btn_Exit_Click); // // tbx_interval // C#啟動Windows服務的窗體程序this.tbx_interval.BorderStyle = System.windows.Forms.BorderStyle.FixedSingle; this.tbx_interval.ForeColor = System.Drawing.Color.Red; this.tbx_interval.Location = new System. Drawing.Point(8, 40); this.tbx_interval.Name = "tbx_interval"; this.tbx_interval.TabIndex = 7; this.tbx_interval.Text = "輸入監控間隔(秒)"; this.tbx_interval.MouseDown += new System.windows.Forms.MouseEventHandler( this.tbx_interval_MouseDown); // // timer1 // this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // notifyIcon1 // this.notifyIcon1.Icon = ((System.Drawing.Icon) (resources.GetObject("notifyIcon1.Icon"))); this.notifyIcon1.Text = "雙擊打開WatchService"; this.notifyIcon1.Visible = true; this.notifyIcon1.DoubleClick += new System.EventHandler(this.notifyIcon1_DoubleClick); // // WatchService // C#啟動Windows服務的窗體程序this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.ClientSize = new System.Drawing.Size(328, 102); this.Controls.Add(this.tbx_interval); this.Controls.Add(this.btn_Exit); this.Controls.Add(this.tbx_serviceName); this.Controls.Add(this.lbl_appStatus); this.Controls.Add(this.btn_stopReg); this.Controls.Add(this.btn_startReg); this.Controls.Add(this.btn_stopWatch); this.Controls.Add(this.btn_startWatch); this.MaximizeBox = false; this.Name = "WatchService"; this.ShowInTaskbar = false; this.Text = "WatchService"; this.windowstate = System.windows. Forms.Formwindowstate.Minimized; this.Resize += new System.EventHandler( this.WatchService_Resize); this.Load += new System.EventHandler( this.WatchService_Load); this.ResumeLayout(false); } #endregion private ServiceController scDBService; private string serviceName="MSSqlServer"; // 默認服務名 private int iInterval=60; // 默認監控間隔(秒) /// ﹤summary﹥ ///C#啟動Windows服務的窗體程序/// 應用程序的主入口點。 /// ﹤/summary﹥ [STAThread] static void Main() { Application.Run(new WatchService()); } // 開啟監控 private void btn_startWatch_Click( object sender, System.EventArgs e) { if(this.tbx_serviceName.Text=="") { this.lbl_appStatus.Text="服務名不能為空"; this.tbx_serviceName.Focus(); return; } if(this.tbx_interval.Text=="") { this.lbl_appStatus.Text="服務監控間隔不能為空"; this.tbx_interval.Focus(); return; } serviceName=this.tbx_serviceName.Text; iInterval=int.Parse(this.tbx_interval.Text); this.timer1.Interval=iInterval*1000; startService(); } // 開啟隨機啟動 private void btn_startReg_Click( object sender, System.EventArgs e) { try { string dir=Directory.GetCurrentDirectory(); dir+="\\WatchService.exe"; RegistryKey akey=Registry.LocalMachine; akey=akey.OpenSubKey(@"SOFTWARE\Microsoft \windows\CurrentVersion\Run",true); akey.SetValue("WatchService",dir); akey.Close(); this.lbl_appStatus.Text="開啟隨機啟動成功。"; } catch(Exception exp) { this.lbl_appStatus.Text="開啟隨機啟動失敗, 原因:"+exp.Message; } } //C#啟動Windows服務的窗體程序private void tbx_serviceName_MouseDown( object sender, System.windows.Forms.MouseEventArgs e) { this.tbx_serviceName.Text=""; } // 關閉隨機啟動 private void btn_stopReg_Click(object sender, System.EventArgs e) { try { RegistryKey akey=Registry.LocalMachine; akey=akey.OpenSubKey(@"SOFTWARE\Microsoft \windows\CurrentVersion\Run",true); akey.SetValue("WatchService",false); akey.Close(); this.lbl_appStatus.Text="關閉隨機啟動成功。"; } catch(Exception exp) { this.lbl_appStatus.Text="關閉隨機啟動失敗,原因:"+exp.Message; } } private void btn_Exit_Click(object sender, System.EventArgs e) { Application.Exit(); } /// ﹤summary﹥ /// 開啟指定的windows服務 ///C#啟動Windows服務的窗體程序/// ﹤/summary﹥ private void startService() { try { scDBService=new ServiceController(serviceName); ServiceController[] scAllService= ServiceController.GetServices(); int i=0; while(i﹤scAllService.Length) { if(scAllService[i].DisplayName==serviceName) { if(scDBService.Status.Equals(ServiceControllerStatus.Stopped)) { this.lbl_appStatus.Text=serviceName+" 服務正在啟動……"; scDBService.Start(); } else if(scDBService.Status.Equals( ServiceControllerStatus.Running)) { this.lbl_appStatus.Text=serviceName+" 服務正在運行……"; } if(!this.timer1.Enabled) this.timer1.Start(); return; } else { i++; } } this.lbl_appStatus.Text=serviceName+" 服務并沒有安裝在本機上,請檢查。"; if(this.timer1.Enabled) this.timer1.Stop(); } catch(Exception exp) { this.lbl_appStatus.Text=serviceName+ "服務啟動失敗,原因:"+exp.Message; } } // 監控時鐘 private void timer1_Tick(object sender, System.EventArgs e) { startService(); } private void tbx_interval_MouseDown(object sender, System.windows.Forms.MouseEventArgs e) { this.tbx_interval.Text=""; } // 窗體加載后即最小化到托盤區 private void WatchService_Load( object sender, System.EventArgs e) { this.Hide(); this.notifyIcon1.Visible=true; startService(); } // 窗體最小化 private void WatchService_Resize( object sender, System.EventArgs e) { if (this.windowstate==Formwindowstate.Minimized) { this.Hide(); this.notifyIcon1.Visible=true; } } // 托盤區圖標操作 private void notifyIcon1_DoubleClick( object sender, System.EventArgs e) { this.Visible = true; this.windowstate = Formwindowstate.Normal; this.notifyIcon1.Visible = false; } // 停止監控 private void btn_stopWatch_Click( object sender, System.EventArgs e) { this.timer1.Stop(); } } }
到此,關于“C#如何啟動Windows服務的窗體程序”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。