写了个工具,需要调用服务,为了方便使用,将开启和关闭服务的操作放到代码中,这样就不用每次都手动的去打开关闭服务了。
根据本人亲试,需要补充的是,在打开服务之后,最好调用刷新方法,刷新一下,不然虽然服务开了,但是获取到的状态还是没变。
//添加引用
System.ServiceProcess;
//声明
ServiceController service = new System.ServiceProcess.ServiceController(服务名);
//开始服务
service.Start();
//关闭服务
service.Stop();
//暂停服务
service.Pause();
//继续服务
service.Continue();
//刷新服务
service.Refresh();
//判断当前服务状态
if (service.Status != ServiceControllerStatus.Running)
{
service.Start();
service.Refresh();
}
服务状态:
ServiceControllerStatus 枚举 指示服务的当前状态
成员
成员名称 | 说明 |
---|---|
ContinuePending | 服务即将继续。这对应于 Win32 SERVICE_CONTINUE_PENDING 常数,该常数定义为 0x00000005。 |
Paused | 服务已暂停。这对应于 Win32 SERVICE_PAUSED 常数,该常数定义为 0x00000007。 |
PausePending | 服务即将暂停。这对应于 Win32 SERVICE_PAUSE_PENDING 常数,该常数定义为 0x00000006。 |
Running | 服务正在运行。这对应于 Win32 SERVICE_RUNNING 常数,该常数定义为 0x00000004。 |
StartPending | 服务正在启动。这对应于 Win32 SERVICE_START_PENDING 常数,该常数定义为 0x00000002。 |
Stopped | 服务未运行。这对应于 Win32 SERVICE_STOPPED 常数,该常数定义为 0x00000001。 |
StopPending | 服务正在停止。这对应于 Win32 SERVICE_STOP_PENDING 常数,该常数定义为 0x00000003。 |