ENUM_SERVICE_STATUS_PROCESS infoLevel = new ENUM_SERVICE_STATUS_PROCESS();
if (!EnumServicesStatusEx(handle, SC_ENUM_PROCESS_INFO, (int)ServiceType.SERVICE_WIN32, (int)ServiceStateRequest.SERVICE_STATE_ALL, IntPtr.Zero, 0, out iBytesNeeded, out iServicesReturned, ref iResumeHandle, null))
{
// allocate our memory to receive the data for all the services (including the names)
buf = Marshal.AllocHGlobal((int)iBytesNeeded);
if (!EnumServicesStatusEx(handle, SC_ENUM_PROCESS_INFO, (int)ServiceType.SERVICE_WIN32, (int)ServiceStateRequest.SERVICE_STATE_ALL, buf, iBytesNeeded, out iBytesNeeded, out iServicesReturned, ref iResumeHandle, null))
throw new Win32Exception(Marshal.GetLastWin32Error());
ENUM_SERVICE_STATUS_PROCESS serviceStatus;
// check if 64 bit system which has different pack sizes
if (IntPtr.Size == 8)
{
long pointer = buf.ToInt64();
for (int i = 0; i < (int)iServicesReturned; i++)
{
serviceStatus = (ENUM_SERVICE_STATUS_PROCESS)Marshal.PtrToStructure(new IntPtr(pointer),
typeof(ENUM_SERVICE_STATUS_PROCESS));
result.Add(serviceStatus);
// incremement by sizeof(ENUM_SERVICE_STATUS_PROCESS) allow Packing of 8
pointer += ENUM_SERVICE_STATUS_PROCESS.SizePack8;
}
}
else
{
int pointer = buf.ToInt32();
for (int i = 0; i < (int)iServicesReturned; i++)
{
serviceStatus = (ENUM_SERVICE_STATUS_PROCESS)Marshal.PtrToStructure(new IntPtr(pointer),
typeof(ENUM_SERVICE_STATUS_PROCESS));
result.Add(serviceStatus);
// incremement by sizeof(ENUM_SERVICE_STATUS_PROCESS) allow Packing of 4
pointer += ENUM_SERVICE_STATUS_PROCESS.SizePack4;
}
}
}
}
}
catch(Exception e)
{
;
}
finally
{
if (handle != IntPtr.Zero)
CloseServiceHandle(handle);
if (buf != IntPtr.Zero)
Marshal.FreeHGlobal(buf);
}
return result.ToArray();
}
private const int SC_ENUM_PROCESS_INFO = 0;
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool EnumServicesStatusEx(IntPtr hSCManager,
int infoLevel, int dwServiceType,
int dwServiceState, IntPtr lpServices, UInt32 cbBufSize,
out uint pcbBytesNeeded, out uint lpServicesReturned,
ref uint lpResumeHandle, string pszGroupName);
[StructLayout(LayoutKind.Sequential)]
internal struct SERVICE_STATUS_PROCESS
{
public int serviceType;
public int currentState;
public int controlsAccepted;
public int win32ExitCode;
public int serviceSpecificExitCode;
public int checkPoint;
public int waitHint;
public int processId;
public int serviceFlags;
}
helpful tips or sample code to share for using this API in managed code?
corrections to the existing content?
variations of the signature you want to share?
additional languages you want to include?
Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).