C#使用ServiceController控制windows服务

C#中,使用ServiceController类控制windows服务,使用之前要先添加引用:System.ServiceProcess,然后在命名空间中引用:using System.ServiceProcess。下面举例获取本机的所有已安装的Windows服务和应用,然后查找某一应用活服务是否已经安装。

代码:

 
  1. using System;

  2. using System.Collections.Generic;

  3. using System.ComponentModel;

  4. using System.Data;

  5. using System.Drawing;

  6. using System.Linq;

  7. using System.Text;

  8. using System.Windows.Forms;

  9. using System.ServiceProcess;

  10.  
  11. namespace 判断机器中是否安装了某项服务或者应用

  12. {

  13. public partial class Form1 : Form

  14. {

  15. public Form1()

  16. {

  17. InitializeComponent();

  18. }

  19. ServiceController[] Services = ServiceController.GetServices();

  20. private bool ExistSth()

  21. {

  22. bool exist = false;

  23. for (int i = 0; i < Services.Length; i++)

  24. {

  25. if (Services[i].DisplayName.ToString() == textBox1.Text.Trim())

  26. exist = true;

  27. }

  28. return exist;

  29. }

  30. private void button1_Click(object sender, EventArgs e)

  31. {

  32. if (ExistSth())

  33. MessageBox.Show("已安装");

  34. else

  35. MessageBox.Show("未安装");

  36. }

  37.  
  38. private void Form1_Load(object sender, EventArgs e)

  39. {

  40. for (int i = 0; i < Services.Length; i++)

  41. listBox1.Items.Add(Services[i].DisplayName.ToString());

  42. }

  43. }

  44. }


       假设某一服务名为ServicesName, 编写开始服务,停止服务,重启服务的代码如下:

 
  1. private ServiceController _controller;

  2.  
  3. private void StopService()

  4. {

  5. this._controller = new ServiceController("ServicesName");

  6. this._controller.Stop();

  7. this._controller.WaitForStatus(ServiceControllerStatus.Stopped);

  8. this._controller.Close();

  9. }

  10.  
  11. private void StartService()

  12. {

  13. this._controller = new ServiceController("ServicesName");

  14. this._controller.Start();

  15. this._controller.WaitForStatus(ServiceControllerStatus.Running);

  16. this._controller.Close();

  17. }

  18.  
  19. private void ResetService()

  20. {

  21. this._controller = new ServiceController("ServicesName");

  22. this._controller.Stop();

  23. this._controller.WaitForStatus(ServiceControllerStatus.Stopped);

  24. this._controller.Start();

  25. this._controller.WaitForStatus(ServiceControllerStatus.Running);

  26. this._controller.Close();

  27. }

猜你喜欢

转载自blog.csdn.net/lxrj2008/article/details/81316485
今日推荐