首页

C#实现获取并操作(启动、暂停、重启、停止)某台电脑 Windows 服务

c#

2020-8-25

C#实现获取并操作某台电脑 的所有Windows 服务,

实现的功能有:选中某一个服务,然后对其进行 启动服务、暂停服务、停止服务、重启服务等操作

获取服务代码:

		private void GetServices_Button_Click(object sender, System.EventArgs e)
		{
			this.listBox1.Items.Clear();
			if ( this.textBox1.Text.Equals("") )
			{
				svcs=ServiceController.GetServices();
				this.label2.Text="Services on then local machine";
			}
			else
			{
				try
				{
					svcs=ServiceController.GetServices(this.textBox1.Text);
					this.textBox1.Text="";
					return;
				}
				catch
				{
					MessageBox.Show("Unable to fine the computer!");
					this.textBox1.Text="";
					return;
				}
			}
			svcs_enum=svcs.GetEnumerator();
			System.ServiceProcess.ServiceController sc;
			while(svcs_enum.MoveNext())
			{
				sc=(ServiceController)svcs_enum.Current;
				this.listBox1.Items.Add(sc.ServiceName);
			}
		}

服务操作代码:

 

			ServiceController sc;
			sc=(ServiceController)svcs.GetValue(this.listBox1.SelectedIndex);
			enable_disable_MenuItems(sc);
			try
			{
				sc.Stop();
				sc.WaitForStatus(ServiceControllerStatus.Stopped);
				MessageBox.Show("Service " sc.ServiceName " stopped on "  sc.MachineName  " !");
			}
			catch
			{
				MessageBox.Show("Unable to stop " sc.ServiceName " service!");
			}

 

 

			ServiceController sc;
			sc=(ServiceController)svcs.GetValue(this.listBox1.SelectedIndex);
			enable_disable_MenuItems(sc);
			try
			{
				sc.Pause();
				sc.WaitForStatus(ServiceControllerStatus.Paused);
				MessageBox.Show("Service " sc.ServiceName " paused on "  sc.MachineName  " !");
			}
			catch
			{
				MessageBox.Show("Unable to pause " sc.ServiceName " service!");
			}

 

资源下载此资源下载价格为2D币(VIP免费),请先
资源文件列表
ServiceController/App.ico , 1078
ServiceController/AssemblyInfo.cs , 1859
ServiceController/bin/Debug/ServiceController.exe , 32768
ServiceController/bin/Debug/ServiceController.pdb , 19968
ServiceController/ControllerForm.cs , 11234
ServiceController/ControllerForm.resx , 12230
ServiceController/obj/Debug/ServiceControlle.ServiceControllerForm.resources , 9385
ServiceController/obj/Debug/ServiceController.exe , 32768
ServiceController/obj/Debug/ServiceController.pdb , 19968
ServiceController/obj/Debug/ServiceController.projdata , 8840
ServiceController/ServiceController.csproj , 4990
ServiceController/ServiceController.csproj.user , 1804
ServiceController/ServiceController.sln , 919
ServiceController/ServiceController.suo , 8192
没有账号? 忘记密码?

社交账号快速登录