EnumServicesStatus (advapi32)
Last changed: -74.56.93.131

.
Summary
The EnumServicesStatus function enumerates services in the specified service control manager database. The name and status of each service are provided.

C# Signature:

[DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern bool EnumServicesStatus( IntPtr hSCManager,
                    SERVICE_TYPES dwServiceType,
                    SERVICE_STATES dwServiceState,
                    IntPtr lpServices,
                    int cbBufSize,
                    ref int pcbBytesNeeded,
                    ref int lpServicesReturned,
                    ref int lpResumeHandle );

VB Signature:

Declare Function EnumServicesStatus Lib "advapi32.dll" (TODO) As TODO

User-Defined Types:

SERVICE_STATES, SERVICE_TYPES, ENUM_SERVICE_STATUS

Notes:

See also: OpenSCManager

Tips & Tricks:

Please add some!

Sample Code:

IntPtr handle = OpenSCManager( null, null, SCM_ACCESS.SC_MANAGER_ALL_ACCESS );
if ( handle != IntPtr.Zero )
{
     int iBytesNeeded = 0;
     int iServicesReturned = 0;
     int iResumeHandle = 0;

     if ( !EnumServicesStatus( handle,
                   SERVICE_TYPES.SERVICE_WIN32,
                   SERVICE_STATES.SERVICE_STATE_ALL,
                   IntPtr.Zero,
                   0,
                   ref iBytesNeeded,
                   ref iServicesReturned,
                   ref iResumeHandle ) )
     {
     // Don't forget to test for ERROR_MORE_DATA before proceeding (removed for brevity)
     IntPtr buf = Marshal.AllocHGlobal( (int) iBytesNeeded );
     if ( !EnumServicesStatus( handle,
                   SERVICE_TYPES.SERVICE_WIN32,
                   SERVICE_STATES.SERVICE_STATE_ALL,
                   buf,
                   iBytesNeeded,
                   ref iBytesNeeded,
                   ref iServicesReturned,
                   ref iResumeHandle ) )
     {
         Debug.WriteLine("EnumServicesStatus Failed " + Marshal.GetLastWin32Error() );
     }
     else
     {
         ENUM_SERVICE_STATUS serviceStatus;
         int iPtr = buf.ToInt32();
         for ( int i = 0 ; i < (int) iServicesReturned; i++ )
         {
         serviceStatus = (ENUM_SERVICE_STATUS) Marshal.PtrToStructure( new IntPtr(iPtr),  typeof(ENUM_SERVICE_STATUS) );
         Debug.WriteLine("Service " + serviceStatus.pServiceName );
         iPtr += ENUM_SERVICE_STATUS.SizeOf;
         }
         Debug.WriteLine("EnumServicesStatus Success");
     }
     }
}

Alternative Managed API:

Do you know one? Please contribute it!

Documentation