static bool StopService(Options opt) { bool bResult = false; try { bool IsWindows = System.Runtime.InteropServices.RuntimeInformation .IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows); if (IsWindows == true) { ServiceControlManager mgr = ServiceControlManager.Connect(Win32ServiceInterop.Wrapper, null, null, ServiceControlManagerAccessRights.All); if ((mgr != null) && (mgr.IsInvalid != true)) { ServiceHandle h = mgr.OpenService(ServiceName, ServiceControlAccessRights.All); if (h != null) { ServiceStatusProcess status = new ServiceStatusProcess(); uint reason = (uint)StopReasonMinorReasonFlags.SERVICE_STOP_REASON_MINOR_MAINTENANCE | (uint)StopReasonMajorReasonFlags.SERVICE_STOP_REASON_MAJOR_NONE | (uint)StopReasonFlags.SERVICE_STOP_REASON_FLAG_UNPLANNED; ServiceStatusParam param = new ServiceStatusParam(reason, status); int s = Marshal.SizeOf <ServiceStatusParam>(); var lpParam = Marshal.AllocHGlobal(s); Marshal.StructureToPtr(param, lpParam, fDeleteOld: false); if (Win32ServiceInterop.ControlServiceExW(h, (uint)ServiceControlCommandFlags.SERVICE_CONTROL_STOP, (uint)ServiceControlCommandReasonFlags.SERVICE_CONTROL_STATUS_REASON_INFO, lpParam) == true) { bResult = true; } else { opt.LogError("Stop feature: can't stop Service: " + ServiceName + " ErrorCode: " + Marshal.GetLastWin32Error().ToString()); } } else { opt.LogError("Stop feature: can't open Service: " + ServiceName); } } else { opt.LogError("Stop feature: can't open ServiceManager"); } } else { opt.LogError("Stop feature: this service is not available on the current platform"); } } catch (Exception ex) { opt.LogError("Stop feature: exception: " + ex.Message); } return(bResult); }
private static int GetServiceProcessId(ServiceController sc) { IntPtr zero = IntPtr.Zero; try { UInt32 dwBytesNeeded; // Call once to figure the size of the output buffer. QueryServiceStatusEx(sc.ServiceHandle, SC_STATUS_PROCESS_INFO, zero, 0, out dwBytesNeeded); if (Marshal.GetLastWin32Error() == ERROR_INSUFFICIENT_BUFFER) { // Allocate required buffer and call again. zero = Marshal.AllocHGlobal((int)dwBytesNeeded); if (QueryServiceStatusEx( sc.ServiceHandle, SC_STATUS_PROCESS_INFO, zero, dwBytesNeeded, out dwBytesNeeded)) { var ssp = new ServiceStatusProcess(); Marshal.PtrToStructure(zero, ssp); return((int)ssp.dwProcessId); } } } finally { if (zero != IntPtr.Zero) { Marshal.FreeHGlobal(zero); } } return(-1); }
public static void ReadStatuses(ref ServiceStatusProcess service) { _services.Add(service); }