C#啟動(dòng)Windows服務(wù)的窗體程序淺析
C#啟動(dòng)Windows服務(wù)的窗體程序的由來(lái):最近應(yīng)客戶的要求,做了一個(gè)定時(shí)監(jiān)控WINDOWS服務(wù)的程序,要做到隨機(jī)啟動(dòng),定時(shí)監(jiān)控指定的服務(wù),如果沒有開啟則開啟,由于時(shí)間倉(cāng)促,沒有經(jīng)過(guò)長(zhǎng)時(shí)間的服務(wù)器端運(yùn)行,現(xiàn)將思路及代碼公布,以后有改進(jìn)會(huì)及時(shí)更新:
一、C#啟動(dòng)Windows服務(wù)的窗體程序思路:
本程序的核心在于隨機(jī)啟動(dòng)和WINDOWS服務(wù)上,對(duì)于隨機(jī)啟動(dòng),引入Microsoft.Win32命名空間,利用RegistryKey類即可完成對(duì)注冊(cè)表的增、刪、改等操作;對(duì)于WINDOWS服務(wù),引入System.ServiceProcess命名空間,利用ServiceController類即可完成對(duì)系統(tǒng)服務(wù)的啟動(dòng)、停止、查詢等操作。改日就測(cè)試程序的穩(wěn)定性及資源消耗率等指標(biāo)。
二、C#啟動(dòng)Windows服務(wù)的窗體程序代碼如下,這里程序默認(rèn)為開啟MSSQLSERVER服務(wù),并添加了托盤區(qū)圖標(biāo),可以在啟動(dòng)時(shí)或啟動(dòng)后最小化到托盤區(qū):
- using System; //C#啟動(dòng)Windows服務(wù)的窗體程序
- 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 的摘要說(shuō)明,C#啟動(dòng)Windows服務(wù)的窗體程序
- /// ﹤/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#啟動(dòng)Windows服務(wù)的窗體程序
- // windows 窗體設(shè)計(jì)器支持所必需的
- //
- InitializeComponent();
- //
- // TODO: 在 InitializeComponent
- //調(diào)用后添加任何構(gòu)造函數(shù)代碼
- //
- }
- /// ﹤summary﹥
- ///C#啟動(dòng)Windows服務(wù)的窗體程序
- /// 清理所有正在使用的資源。
- /// ﹤/summary﹥
- protected override void Dispose( bool disposing )
- {
- if( disposing )
- {
- if (components != null)
- {
- components.Dispose();
- }
- }
- base.Dispose( disposing );
- }
- #region windows 窗體設(shè)計(jì)器生成的代碼
- /// ﹤summary﹥
- /// 設(shè)計(jì)器支持所需的方法 - 不要使用代碼編輯器修改
- /// 此方法的內(nèi)容。
- /// ﹤/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#啟動(dòng)Windows服務(wù)的窗體程序
- 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 = "開始監(jiān)控";
- 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 = "停止監(jiān)控";
- //
- // btn_startReg
- // C#啟動(dòng)Windows服務(wù)的窗體程序
- 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 = "開啟隨機(jī)啟動(dòng)";
- 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 = "關(guān)閉隨機(jī)啟動(dòng)";
- this.btn_stopReg.Click += new
- System.EventHandler(this.btn_stopReg_Click);
- //
- // lbl_appStatus
- // C#啟動(dòng)Windows服務(wù)的窗體程序
- 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 = "輸入服務(wù)名";
- 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#啟動(dòng)Windows服務(wù)的窗體程序
- 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 = "輸入監(jiān)控間隔(秒)";
- 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#啟動(dòng)Windows服務(wù)的窗體程序
- 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";
- // 默認(rèn)服務(wù)名
- private int iInterval=60;
- // 默認(rèn)監(jiān)控間隔(秒)
- /// ﹤summary﹥
- ///C#啟動(dòng)Windows服務(wù)的窗體程序
- /// 應(yīng)用程序的主入口點(diǎn)。
- /// ﹤/summary﹥
- [STAThread]
- static void Main()
- {
- Application.Run(new WatchService());
- }
- // 開啟監(jiān)控
- private void btn_startWatch_Click(
- object sender, System.EventArgs e)
- {
- if(this.tbx_serviceName.Text=="")
- {
- this.lbl_appStatus.Text="服務(wù)名不能為空";
- this.tbx_serviceName.Focus();
- return;
- }
- if(this.tbx_interval.Text=="")
- {
- this.lbl_appStatus.Text="服務(wù)監(jiān)控間隔不能為空";
- this.tbx_interval.Focus();
- return;
- }
- serviceName=this.tbx_serviceName.Text;
- iInterval=int.Parse(this.tbx_interval.Text);
- this.timer1.Interval=iInterval*1000;
- startService();
- }
- // 開啟隨機(jī)啟動(dòng)
- 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="開啟隨機(jī)啟動(dòng)成功。";
- }
- catch(Exception exp)
- {
- this.lbl_appStatus.Text="開啟隨機(jī)啟動(dòng)失敗,
- 原因:"+exp.Message;
- }
- } //C#啟動(dòng)Windows服務(wù)的窗體程序
- private void tbx_serviceName_MouseDown(
- object sender, System.windows.Forms.MouseEventArgs e)
- {
- this.tbx_serviceName.Text="";
- }
- // 關(guān)閉隨機(jī)啟動(dòng)
- 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="關(guān)閉隨機(jī)啟動(dòng)成功。";
- }
- catch(Exception exp)
- {
- this.lbl_appStatus.Text="關(guān)閉隨機(jī)啟動(dòng)失敗,原因:"+exp.Message;
- }
- }
- private void btn_Exit_Click(object sender, System.EventArgs e)
- {
- Application.Exit();
- }
- /// ﹤summary﹥
- /// 開啟指定的windows服務(wù)
- ///C#啟動(dòng)Windows服務(wù)的窗體程序
- /// ﹤/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+"
- 服務(wù)正在啟動(dòng)……";
- scDBService.Start();
- }
- else if(scDBService.Status.Equals(
- ServiceControllerStatus.Running))
- {
- this.lbl_appStatus.Text=serviceName+"
- 服務(wù)正在運(yùn)行……";
- }
- if(!this.timer1.Enabled) this.timer1.Start();
- return;
- }
- else
- {
- i++;
- }
- }
- this.lbl_appStatus.Text=serviceName+"
- 服務(wù)并沒有安裝在本機(jī)上,請(qǐng)檢查。";
- if(this.timer1.Enabled) this.timer1.Stop();
- }
- catch(Exception exp)
- {
- this.lbl_appStatus.Text=serviceName+
- "服務(wù)啟動(dòng)失敗,原因:"+exp.Message;
- }
- }
- // 監(jiān)控時(shí)鐘
- 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="";
- }
- // 窗體加載后即最小化到托盤區(qū)
- 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;
- }
- }
- // 托盤區(qū)圖標(biāo)操作
- private void notifyIcon1_DoubleClick(
- object sender, System.EventArgs e)
- {
- this.Visible = true;
- this.windowstate = Formwindowstate.Normal;
- this.notifyIcon1.Visible = false;
- }
- // 停止監(jiān)控
- private void btn_stopWatch_Click(
- object sender, System.EventArgs e)
- {
- this.timer1.Stop();
- }
- }
- }
C#啟動(dòng)Windows服務(wù)的窗體程序的基本情況就向你介紹到這里,希望對(duì)你了解和學(xué)習(xí)C#啟動(dòng)Windows服務(wù)的窗體程序有所幫助。
【編輯推薦】