private static void StopServiceExe(string hostname) { ServiceControlHandle con = NativeMethods.OpenSCManager(hostname, null, NativeMethods.SCM_ACCESS.SC_MANAGER_ALL_ACCESS); ServiceControlHandle m_serv = NativeMethods.OpenService(con, GlobalVars.ServiceName, NativeMethods.SERVICE_ACCESS.SERVICE_ALL_ACCESS); NativeMethods.SERVICE_STATUS stat = new NativeMethods.SERVICE_STATUS(); bool res = NativeMethods.ControlService(m_serv, NativeMethods.SERVICE_CONTROL.STOP, ref stat); Console.WriteLine("[*] Stop service result: " + res); // TODO: Code to halt execution until the service has finally stopped, to continue another task afterwards. while (!res) { res = NativeMethods.QueryServiceStatus(m_serv, ref stat); if (stat.dwCurrentState == NativeMethods.SERVICE_STATE.SERVICE_STOPPED) { break; } if (!res) { int error = Marshal.GetLastWin32Error(); if (error == 0x6) { Console.WriteLine("[*] StopServiceExe ERROR_INVALID_HANDLE"); break; } if (error == 0x5) { Console.WriteLine("[*] StopServiceExe ERROR_ACCESS_DENIED"); break; } } Console.WriteLine("[*] Waiting for it to stop ..."); Thread.Sleep(5); } }
public static extern ServiceControlHandle CreateService( ServiceControlHandle serviceControlManagerHandle, string lpSvcName, string lpDisplayName, SERVICE_ACCESS dwDesiredAccess, SERVICE_TYPES dwServiceType, SERVICE_START_TYPES dwStartType, SERVICE_ERROR_CONTROL dwErrorControl, string lpPathName, string lpLoadOrderGroup, IntPtr lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword);
public static extern int DeleteService(ServiceControlHandle serviceHandle);
public static extern ServiceControlHandle OpenService(ServiceControlHandle serviceControlManagerHandle, string lpSvcName, SERVICE_ACCESS dwDesiredAccess);
public static extern int StartService(ServiceControlHandle serviceHandle, int dwNumServiceArgs, string lpServiceArgVectors);
public static extern bool QueryServiceStatus(ServiceControlHandle hService, ref SERVICE_STATUS dwServiceStatus);
public static extern bool ControlService(ServiceControlHandle hService, SERVICE_CONTROL dwControl, ref SERVICE_STATUS lpServiceStatus);