/// <summary> /// Determine whether the specified service is configured to trigger start /// </summary> /// <param name="serviceName">The name of the service</param> /// <returns></returns> public static bool IsTriggerStartService(string serviceName) { // Open the local default service control manager database SafeServiceHandle schSCManager = NativeMethods.OpenSCManager(null, null, ServiceControlAccessRights.SC_MANAGER_CONNECT); if (schSCManager.IsInvalid) { // If the handle is invalid, get the last Win32 error and throw a // Win32Exception throw new Win32Exception(); } try { // Try to open the service to query its config SafeServiceHandle schService = NativeMethods.OpenService(schSCManager, serviceName, ServiceAccessRights.SERVICE_QUERY_CONFIG); if (schService.IsInvalid) { // If the handle is invalid, get the last Win32 error and throw a // Win32Exception throw new Win32Exception(); } try { return(IsTriggerStartService(schService)); } finally { schService.Close(); } } finally { schSCManager.Close(); } }
/// <summary> /// Set the service to trigger-start when the first IP address on the TCP/IP /// networking stack becomes available, and trigger-stop when the last IP /// address on the TCP/IP networking stack becomes unavailable. /// </summary> /// <param name="serviceName">The name of the service</param> public static void SetServiceTriggerStartOnIPAddressArrival(string serviceName) { // Open the local default service control manager database SafeServiceHandle schSCManager = NativeMethods.OpenSCManager(null, null, ServiceControlAccessRights.SC_MANAGER_CONNECT); if (schSCManager.IsInvalid) { // If the handle is invalid, get the last Win32 error and throw a // Win32Exception throw new Win32Exception(); } try { // Try to open the service with the SERVICE_CHANGE_CONFIG access right SafeServiceHandle schService = NativeMethods.OpenService(schSCManager, serviceName, ServiceAccessRights.SERVICE_CHANGE_CONFIG); if (schService.IsInvalid) { // If the handle is invalid, get the last Win32 error and throw a // Win32Exception throw new Win32Exception(); } try { SetServiceTriggerStartOnIPAddressArrival(schService); } finally { schService.Close(); } } finally { schSCManager.Close(); } }