Here is the situation:
I have been called upon to work with InstallAnywhere 8, a Java-based installer IDE, of sorts, that allows starting and stopping of windows ser
Here's a straignt C# / P/Invoke solution.
///
/// Returns true if the specified service is running, or false if it is not present or not running.
///
/// Name of the service to check.
/// Returns true if the specified service is running, or false if it is not present or not running.
static bool IsServiceRunning(string serviceName)
{
bool rVal = false;
try
{
IntPtr smHandle = NativeMethods.OpenSCManager(null, null, NativeMethods.ServiceAccess.ENUMERATE_SERVICE);
if (smHandle != IntPtr.Zero)
{
IntPtr svHandle = NativeMethods.OpenService(smHandle, serviceName, NativeMethods.ServiceAccess.ENUMERATE_SERVICE);
if (svHandle != IntPtr.Zero)
{
NativeMethods.SERVICE_STATUS servStat = new NativeMethods.SERVICE_STATUS();
if (NativeMethods.QueryServiceStatus(svHandle, servStat))
{
rVal = servStat.dwCurrentState == NativeMethods.ServiceState.Running;
}
NativeMethods.CloseServiceHandle(svHandle);
}
NativeMethods.CloseServiceHandle(smHandle);
}
}
catch (System.Exception )
{
}
return rVal;
}
public static class NativeMethods
{
[DllImport("AdvApi32")]
public static extern IntPtr OpenSCManager(string machineName, string databaseName, ServiceAccess access);
[DllImport("AdvApi32")]
public static extern IntPtr OpenService(IntPtr serviceManagerHandle, string serviceName, ServiceAccess access);
[DllImport("AdvApi32")]
public static extern bool CloseServiceHandle(IntPtr serviceHandle);
[DllImport("AdvApi32")]
public static extern bool QueryServiceStatus(IntPtr serviceHandle, [Out] SERVICE_STATUS status);
[Flags]
public enum ServiceAccess : uint
{
ALL_ACCESS = 0xF003F,
CREATE_SERVICE = 0x2,
CONNECT = 0x1,
ENUMERATE_SERVICE = 0x4,
LOCK = 0x8,
MODIFY_BOOT_CONFIG = 0x20,
QUERY_LOCK_STATUS = 0x10,
GENERIC_READ = 0x80000000,
GENERIC_WRITE = 0x40000000,
GENERIC_EXECUTE = 0x20000000,
GENERIC_ALL = 0x10000000
}
public enum ServiceState
{
Stopped = 1,
StopPending = 3,
StartPending = 2,
Running = 4,
Paused = 7,
PausePending =6,
ContinuePending=5
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class SERVICE_STATUS
{
public int dwServiceType;
public ServiceState dwCurrentState;
public int dwControlsAccepted;
public int dwWin32ExitCode;
public int dwServiceSpecificExitCode;
public int dwCheckPoint;
public int dwWaitHint;
};
}