前面講述了如何創建和安裝服務(創建windows服務),下面把啟動、停止、判斷是否啟動的方法也寫一下。 [csharp] /// <summary> /// 判斷是否安裝了某個服務 /// </summary> /// <param name="serviceName"></param> /// <returns></returns> public static bool ISWindowsServiceInstalled(string serviceName) { try { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController service in services) { if (service.ServiceName == serviceName) { return true; } } return false; } catch { return false; } } [csharp /// <summary> /// 啟動某個服務 /// </summary> /// <param name="serviceName"></param> public static void StartService(string serviceName) { try { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController service in services) { if (service.ServiceName == serviceName) { service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 30)); } } } catch { } } [csharp] /// <summary> /// 停止某個服務 /// </summary> /// <param name="serviceName"></param> public static void StopService(string serviceName) { try { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController service in services) { if (service.ServiceName == serviceName) { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 30)); } } } catch { } } [csharp] /// <summary> /// 判斷某個服務是否啟動 /// </summary> /// <param name="serviceName"></param> public static bool ISStart(string serviceName) { bool result = true; try { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController service in services) { if (service.ServiceName == serviceName) { if ((service.Status == ServiceControllerStatus.Stopped) || (service.Status == ServiceControllerStatus.StopPending)) { result = false; } } } } catch { } return result; }