启动和停止一个服务,修改服务的启动类型 Start and Stop Service for windows

  public void PreTest()
        {
            SetServiceLaunch(); // 修改服务的启动类型
            ServiceController sc = new ServiceController("GFIProxy");
            if ((sc.Status.Equals(ServiceControllerStatus.Stopped)) || (sc.Status.Equals(ServiceControllerStatus.StopPending)))
            {
                sc.Start(); //启动服务
            }
        }
        public void PostTest()
        {
            SetServiceLaunch();
            ServiceController sc = new ServiceController("GFIProxy");
            if ((sc.Status.Equals(ServiceControllerStatus.Running)) || (sc.Status.Equals(ServiceControllerStatus.StartPending)))
            {
                sc.Stop();
                sc.Refresh();
            }
        }

  public void SetServiceLaunch()
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\GFIProxy", true);
            key.SetValue("Start", 3, RegistryValueKind.DWord); // 3 is 手动启动
        }

 

转载于:https://www.cnblogs.com/VDTy/archive/2012/12/06/2804622.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的Windows监控服务示例,可以监控指定的服务是否停止运行,并在发现服务停止后自动启动服务: ```csharp using System; using System.ServiceProcess; namespace WindowsServiceMonitor { public class ServiceMonitor : ServiceBase { private readonly string _serviceName; private readonly TimeSpan _checkInterval; private readonly System.Timers.Timer _timer; public ServiceMonitor(string serviceName, TimeSpan checkInterval) { _serviceName = serviceName; _checkInterval = checkInterval; _timer = new System.Timers.Timer(_checkInterval.TotalMilliseconds); _timer.Elapsed += Timer_Elapsed; } protected override void OnStart(string[] args) { _timer.Start(); } protected override void OnStop() { _timer.Stop(); } private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { var service = new ServiceController(_serviceName); if (service.Status != ServiceControllerStatus.Running) { Console.WriteLine($"Service {_serviceName} is not running, starting it..."); service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30)); Console.WriteLine($"Service {_serviceName} started."); } } } } ``` 使用方法: 1. 创建一个新的Windows服务项目。 2. 将上述代码复制到Service1.cs文件中。 3. 修改Service1.cs文件中的ServiceMonitor构造函数中的_serviceName和_checkInterval参数,指定要监控的服务名称和检查间隔。 4. 编译并安装Windows服务。 5. 启动Windows服务。 该服务将每隔指定的时间间隔检查指定的服务是否正在运行,如果发现服务停止,则会自动启动服务。在服务启动期间,服务控制台将输出信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值