using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Diagnostics;using System.Collections;///System.ServiceProcess.dllusing System.ServiceProcess;//serviceController1 控件namespace TEST{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private Hashtable ht = new Hashtable(); private string name; private void Form1_Load(object sender, EventArgs e) { LoadServices(); } private void LoadServices() { ht.Clear(); this.lvServices.Items.Clear(); ServiceController[] sc = ServiceController.GetServices(); foreach (ServiceController item in sc) { ListViewItem lviServices = this.lvServices.Items.Add(item.DisplayName); lviServices.SubItems.Add(item.ServiceName.ToString()); lviServices.SubItems.Add(item.Status.ToString()); lviServices.SubItems.Add(item.ServiceType.ToString()); // ht.Add(item.DisplayName, item); } } private void SelectProcess() { if (this.lvServices.SelectedItems.Count != 1) return; name = this.lvServices.SelectedItems[0].SubItems[0].Text; serviceController1 = ht[name] as ServiceController; // 如果当前状态是Stopped,就应该允许用户执行开始服务 this.btnStart.Enabled = (serviceController1.Status == ServiceControllerStatus.Stopped); //如果当前状态不是Stopped并且系统允许停止服务,就应该允许用户执 行停止服务 this.btnStop.Enabled = (serviceController1.CanStop && (!(serviceController1.Status == ServiceControllerStatus.Stopped))); //如果当前状态不是Paused并且系统允许暂停恢复服务,就应该允许用户执行暂停服务 this.btnPause.Enabled = (serviceController1.CanPauseAndContinue && (!(serviceController1.Status == ServiceControllerStatus.Paused))); // 如果当前状态是Paused,就应该允许用户执行恢复服务 this.btnResume.Enabled = (serviceController1.Status == ServiceControllerStatus.Paused); } private void btnStart_Click(object sender, EventArgs e) { this.serviceController1.Start(); LoadServices(); } private void btnPause_Click(object sender, EventArgs e) { this.serviceController1.Pause(); LoadServices(); } private void btnResume_Click(object sender, EventArgs e) { this.serviceController1.Continue(); ; LoadServices(); } private void btnStop_Click(object sender, EventArgs e) { this.serviceController1.Stop(); LoadServices(); } private void lvServices_SelectedIndexChanged(object sender, EventArgs e) { SelectProcess(); } }}