2using System.ComponentModel;
3using System.Runtime.InteropServices;
9 internal class ServiceControlManager : SafeHandle
11 internal ServiceControlManager() : base(IntPtr.Zero, ownsHandle:
true)
15 protected override bool ReleaseHandle()
17 return Win32.CloseServiceHandle(this.handle);
20 public override bool IsInvalid
22 [System.Security.SecurityCritical]
25 return this.handle == IntPtr.Zero;
29 internal static ServiceControlManager Connect(
string machineName,
string databaseName, ServiceControlManagerAccessRights desiredAccessRights)
31 ServiceControlManager mgr =
Win32.OpenSCManagerW(machineName, databaseName, desiredAccessRights);
34 throw new Win32Exception(Marshal.GetLastWin32Error());
39 public ServiceHandle CreateService(
string serviceName,
string displayName,
string binaryPath, ServiceType serviceType,
ServiceStartType startupType, ErrorSeverity errorSeverity,
Win32ServiceCredentials credentials)
41 ServiceHandle service =
Win32.CreateServiceW(
this, serviceName, displayName, ServiceControlAccessRights.All, serviceType, startupType, errorSeverity,
42 binaryPath,
null, IntPtr.Zero,
null, credentials.UserName, credentials.Password);
44 if (service.IsInvalid)
45 throw new Win32Exception(Marshal.GetLastWin32Error());
50 public ServiceHandle OpenService(
string serviceName, ServiceControlAccessRights desiredControlAccess)
52 if (!this.TryOpenService(serviceName, desiredControlAccess, out ServiceHandle service, out Win32Exception errorException))
58 public virtual bool TryOpenService(
string serviceName, ServiceControlAccessRights desiredControlAccess, out ServiceHandle serviceHandle,
59 out Win32Exception errorException)
61 ServiceHandle service =
Win32.OpenServiceW(
this, serviceName, desiredControlAccess);
63 if (service.IsInvalid)
65 errorException =
new Win32Exception(Marshal.GetLastWin32Error());
70 serviceHandle = service;
71 errorException =
null;
Handles interaction with Windows Service API.
ServiceStartType
How the windows service should be started.