public void Dispose() { if (this._svcHandle != null) { this._svcHandle.Dispose(); this._svcHandle = null; } }
internal WinServiceHandle OpenService(string serviceName, WinNativeMethods.ServiceAccessRights desiredAccess) { WinServiceHandle hndle = WinNativeMethods.OpenService(this._svcHandle, serviceName, desiredAccess); if (hndle.IsInvalid) { throw new Win32Exception(Marshal.GetLastWin32Error()); } return(hndle); }
public void SetRestartActions(string serviceName, int restartActionsCount, int resetDays, int delayMinutes, bool restartOnNonCrash) { uint num = (uint)((delayMinutes * 60) * 1000); uint num2 = (uint)(((resetDays * 24) * 60) * 60); WinServiceHandle serviceHandle = null; IntPtr zero = IntPtr.Zero; IntPtr ptr = IntPtr.Zero; IntPtr hglobal = IntPtr.Zero; try { serviceHandle = this.OpenService(serviceName, WinNativeMethods.ServiceAccessRights.SERVICE_CHANGE_CONFIG | WinNativeMethods.ServiceAccessRights.SERVICE_START); hglobal = Marshal.AllocHGlobal((int)(Marshal.SizeOf(typeof(WinNativeMethods.SC_ACTION)) * restartActionsCount)); for (int i = 0; i < restartActionsCount; i++) { WinNativeMethods.SC_ACTION sc_action = new WinNativeMethods.SC_ACTION { Type = WinNativeMethods.SC_ACTION_TYPE.SC_ACTION_RESTART, Delay = num }; Marshal.StructureToPtr(sc_action, (IntPtr)(((long)hglobal) + (i * Marshal.SizeOf(typeof(WinNativeMethods.SC_ACTION)))), false); } WinNativeMethods.SERVICE_FAILURE_ACTIONS structure = new WinNativeMethods.SERVICE_FAILURE_ACTIONS { dwResetPeriod = num2, cActions = (uint)restartActionsCount, lpsaActions = hglobal, lpRebootMsg = null, lpCommand = null }; zero = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WinNativeMethods.SERVICE_FAILURE_ACTIONS))); Marshal.StructureToPtr(structure, zero, false); if (WinNativeMethods.ChangeServiceConfig2(serviceHandle, WinNativeMethods.ServiceConfig2InfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS, zero) == 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); } if (restartOnNonCrash) { WinNativeMethods.SERVICE_FAILURE_ACTIONS_FLAG service_failure_actions_flag = new WinNativeMethods.SERVICE_FAILURE_ACTIONS_FLAG { FailureActionsOnNonCrashFailures = true }; ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WinNativeMethods.SERVICE_FAILURE_ACTIONS_FLAG))); Marshal.StructureToPtr(service_failure_actions_flag, ptr, false); if (WinNativeMethods.ChangeServiceConfig2(serviceHandle, WinNativeMethods.ServiceConfig2InfoLevel.SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, ptr) == 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } } finally { if (zero != IntPtr.Zero) { Marshal.FreeHGlobal(zero); } if (hglobal != IntPtr.Zero) { Marshal.FreeHGlobal(hglobal); } if (ptr != IntPtr.Zero) { Marshal.FreeHGlobal(ptr); } if (serviceHandle != null) { serviceHandle.Dispose(); } } }