[C#] Kiểm tra dịch vụ Services Windows có đang hoạt động
Xin chào các bạn, hôm nay mình sẻ hướng dẫn các bạn cách kiểm tra dịch vụ Services của Windows có đang hoạt động hay không trong lập trình C# winform.
[C#] Detect Status Services Window
Trong lập trình ứng dụng, bạn muốn kiểm tra xem dịch vụ Sqlserver trên máy tính đã được cài đặt hay chưa.
Hoặc dịch vụ services đó đang ở trạng thái nào:
- Running
- Pause
- Stop
Trên giao diện windows, các bạn vào hộp thoại Run gõ services.msc
, để trình quản lý dịch vụ services của windows.
Và dưới đây là demo của mình kiểm tra dịch vụ SQLSERVER đã khởi động hay chưa.
Source code Detect services C#:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DetectServices
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnDetect_Click(object sender, EventArgs e)
{
var service = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == txt_nameService.Text);
if(service == null)
{
lbl_status.Text = $"Services {txt_nameService.Text} Not found!";
}
else
{
lbl_status.Text = $"Services {txt_nameService.Text} is {service.Status.ToString()}";
}
}
}
}
Thanks for watching!