一、 簡介
在我的上一篇文章《.NET開發Windows服務Step By Step》中,向大家介紹了在.NET環境中如何構建自己的Windows服務,由於Windows服務是長期執行的應用程序,它會自動的去執行我們定義的程式碼,然而在某些時候,我們需要更精確的控制其執行,例如:在某個特定時刻讀取數據庫,然後列印一份報表,對於這樣的操作,我們可能隻希望其執行一次,而不是重復的列印,重復的和數據庫I/O,於是我們希望在程式中加以控制,讓其在滿足一定條件下啟動,完成工作之後停止!幸好,像這樣的功能,.NET Framework中提供了一個叫做ServiceController的元件用與實現!該類型在System.ServiceProcess命名空間中定義。使用該元件可以連接到一個特定的服務(對此隻需要將該類型的ServiceName屬性設定為您想要連接的服務名即可),並對該服務進行啟動、停止、暫停、繼續等作業,以及獲得某一電腦上現有的服務清單。下面,我們來看一下ServiceController的使用步驟!
二、 使用步驟
1. 建立ServiceController元件
2. 設定ServiceController元件屬性
3. 編寫程序訪問ServiceController元件的功能
若要建立ServiceController元件以及設定其屬性,請遵循一下步驟:
新建一個Windows應用程序,在工具箱的元件菜單中找到ServiceController元件,並將其拖放到窗體上,打開其屬性窗口設置其屬性,見下圖:
接下來我們需要編寫代碼來訪問ServiceController元件的功能,詳見以下范例。
三、 范例
本范例將實現獲取本機電腦上的服務清單,並將其加入到一個列表控件中,當用戶在列表中選擇某個服務時,可對其進行啟動、停止、暫停、繼續等作業,以下是范例的效果圖:
下面是該范例的程式碼:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.ServiceProcess;
namespace ControlService
{
/// <summary>
/// Form1 的摘要描述。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.ServiceProcess.ServiceController serviceController1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.ListView listView1;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.ColumnHeader columnHeader4;
/// <summary>
/// 設計工具所需的變數。
/// </summary>
private System.ComponentModel.Container components = null;
private string connectServiceName = string.Empty;
private int selectIndex = -1;
public Form1()
{
//
// Windows Form 設計工具支援的必要項
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 呼叫之後加入任何建構函式程式碼
//
}
/// <summary>
/// 清除任何使用中的資源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form 設計工具產生的程式碼
/// <summary>
/// 此為設計工具支援所必須的方法 - 請勿使用程式碼編輯器修改
/// 這個方法的內容。
/// </summary>
private void InitializeComponent()
{
this.serviceController1 = new System.ServiceProcess.ServiceController();
this.label1 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.listView1 = new System.Windows.Forms.ListView();
this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
this.columnHeader3 = new System.Windows.Forms.ColumnHeader();
this.columnHeader4 = new System.Windows.Forms.ColumnHeader();
this.SuspendLayout();
//
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.label1.Location = new System.Drawing.Point(0, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(608, 23);
this.label1.TabIndex = 0;
this.label1.Text = "通過ServiceController元件對Windows服務交互,本范例將與名為MyFirstService的服務交互";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// button1
//
this.button1.Location = new System.Drawing.Point(0, 40);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(136, 24);
this.button1.TabIndex = 1;
this.button1.Text = "啟動服務";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(136, 40);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(136, 24);
this.button2.TabIndex = 2;
this.button2.Text = "停止服務";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button3
//
this.button3.Location = new System.Drawing.Point(272, 40);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(136, 24);
this.button3.TabIndex = 3;
this.button3.Text = "暫停服務";
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// button4
//
this.button4.BackColor = System.Drawing.SystemColors.Control;
this.button4.Location = new System.Drawing.Point(408, 40);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(136, 24);
this.button4.TabIndex = 4;
this.button4.Text = "繼續服務";
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// listView1
//
this.listView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2,
this.columnHeader3,
this.columnHeader4});
this.listView1.FullRowSelect = true;
this.listView1.Location = new System.Drawing.Point(0, 80);
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(608, 240);
this.listView1.TabIndex = 5;
this.listView1.View = System.Windows.Forms.View.Details;
this.listView1.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged);
//
// columnHeader1
//
this.columnHeader1.Text = "全稱";
this.columnHeader1.Width = 200;
//
// columnHeader2
//
this.columnHeader2.Text = "簡稱";
this.columnHeader2.Width = 150;
//
// columnHeader3
//
this.columnHeader3.Text = "狀態";
this.columnHeader3.Width = 100;
//
// columnHeader4
//
this.columnHeader4.Text = "登錄身份";
this.columnHeader4.Width = 100;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 15);
this.ClientSize = new System.Drawing.Size(608, 325);
this.Controls.Add(this.listView1);
this.Controls.Add(this.button4);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.label1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// 應用程式的主進入點。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e)
{
this.GetServiceToListView();
}
private void button1_Click(object sender, System.EventArgs e)
{
// 判斷服務的狀態是否為停止狀態
if (this.serviceController1.Status != ServiceControllerStatus.Stopped)
return;
// 啟動服務
this.serviceController1.Start();
this.GetServiceToListView();
if (this.selectIndex >= 0)
{
this.listView1.Items[this.selectIndex].SubItems[2].Text = "已啟動";
}
}
private void button2_Click(object sender, System.EventArgs e)
{
// 判斷服務是否可以停止
if (this.serviceController1.CanStop == false)
{
MessageBox.Show("當前選定服務不允許停止作業");
return;
}
// 停止服務
this.serviceController1.Stop();
this.GetServiceToListView();
if (this.selectIndex >= 0)
{
this.listView1.Items[this.selectIndex].SubItems[2].Text = "已停止";
}
}
private void button3_Click(object sender, System.EventArgs e)
{
// 判斷服務是否可以暫停或繼續
if (this.serviceController1.CanPauseAndContinue == false)
{
MessageBox.Show("當前選定服務不允許暫停作業");
return;
}
// 暫停服務
this.serviceController1.Pause();
this.GetServiceToListView();
if (this.selectIndex >= 0)
{
this.listView1.Items[this.selectIndex].SubItems[2].Text = "已暫停";
}
}
private void button4_Click(object sender, System.EventArgs e)
{
// 判斷服務是否可以暫停或繼續
if (this.serviceController1.CanPauseAndContinue == false)
{
MessageBox.Show("當前選定服務不允許繼續作業");
return;
}
// 繼續服務
this.serviceController1.Continue();
this.GetServiceToListView();
if (this.selectIndex >= 0)
{
this.listView1.Items[this.selectIndex].SubItems[2].Text = "已啟動";
}
}
// 獲取服務清單並將其加入到ListView中
private void GetServiceToListView()
{
ListViewItem item;
ServiceController[] serviceColl = ServiceController.GetServices();
this.listView1.Items.Clear();
for(int i = 0; i < serviceColl.Length; i++)
{
item = new ListViewItem(serviceColl[i].DisplayName);
item.SubItems.Add(serviceColl[i].ServiceName);
item.SubItems.Add(this.GetServiceStatusText(serviceColl[i].Status.ToString()));
if (serviceColl[i].MachineName == ".")
item.SubItems.Add("SKYBEAN");
else
item.SubItems.Add(serviceColl[i].MachineName);
this.listView1.Items.Add(item);
}
}
private string GetServiceStatusText(string statusName)
{
string statusText = string.Empty;
switch (statusName)
{
case "ContinuePending":
statusText = "已啟動";
break;
case "Paused":
statusText = "已暫停";
break;
case "PausePending":
statusText = "正在暫停";
break;
case "Running":
statusText = "已啟動";
break;
case "StartPending":
statusText = "正在啟動";
break;
case "Stopped":
statusText = "已停止";
break;
case "StopPending":
statusText = "正在停止";
break;
default:
break;
}
return statusText;
}
// 當選中一個ListView項時,將其連接到ServiceController控件
private void listView1_SelectedIndexChanged(object sender, System.EventArgs e)
{
foreach (ListViewItem item in this.listView1.SelectedItems)
{
this.connectServiceName = item.SubItems[1].Text;
this.selectIndex = item.Index;
}
this.serviceController1.ServiceName = this.connectServiceName;
}
}
}
動手試試吧!