1
+ using System ;
2
+ using System . ComponentModel ;
3
+ using System . Runtime . InteropServices ;
4
+ using System . ServiceProcess ;
5
+
6
+ namespace Artemis . Plugins . ChromaSdkHacks ;
7
+
8
+ /// <summary>
9
+ /// http://peterkellyonline.blogspot.com/2011/04/configuring-windows-service.html
10
+ /// </summary>
11
+ public static class ServiceHelper
12
+ {
13
+ [ DllImport ( Advapi32Dll , CharSet = CharSet . Unicode , SetLastError = true ) ]
14
+ private static extern bool ChangeServiceConfig (
15
+ IntPtr hService ,
16
+ uint nServiceType ,
17
+ uint nStartType ,
18
+ uint nErrorControl ,
19
+ string ? lpBinaryPathName ,
20
+ string ? lpLoadOrderGroup ,
21
+ IntPtr lpdwTagId ,
22
+ [ In ] char [ ] ? lpDependencies ,
23
+ string ? lpServiceStartName ,
24
+ string ? lpPassword ,
25
+ string ? lpDisplayName ) ;
26
+
27
+ [ DllImport ( Advapi32Dll , SetLastError = true , CharSet = CharSet . Auto ) ]
28
+ private static extern IntPtr OpenService ( IntPtr hScManager , string lpServiceName , uint dwDesiredAccess ) ;
29
+
30
+ [ DllImport ( Advapi32Dll , EntryPoint = "OpenSCManagerW" , ExactSpelling = true , CharSet = CharSet . Unicode ,
31
+ SetLastError = true ) ]
32
+ private static extern IntPtr OpenSCManager (
33
+ string machineName , string databaseName , uint dwAccess ) ;
34
+
35
+ [ DllImport ( Advapi32Dll , EntryPoint = "CloseServiceHandle" ) ]
36
+ private static extern int CloseServiceHandle ( IntPtr hScObject ) ;
37
+
38
+ private const uint ServiceNoChange = 0xFFFFFFFF ;
39
+ private const uint ServiceQueryConfig = 0x00000001 ;
40
+ private const uint ServiceChangeConfig = 0x00000002 ;
41
+ private const uint ScManagerAllAccess = 0x000F003F ;
42
+ private const string Advapi32Dll = "advapi32.dll" ;
43
+
44
+ public static void ChangeStartMode ( ServiceController svc , ServiceStartMode mode )
45
+ {
46
+ var scManagerHandle = OpenSCManager ( null , null , ScManagerAllAccess ) ;
47
+ if ( scManagerHandle == IntPtr . Zero )
48
+ {
49
+ throw new ExternalException ( "Open Service Manager Error" ) ;
50
+ }
51
+
52
+ var serviceHandle = OpenService (
53
+ scManagerHandle ,
54
+ svc . ServiceName ,
55
+ ServiceQueryConfig | ServiceChangeConfig ) ;
56
+
57
+ if ( serviceHandle == IntPtr . Zero )
58
+ {
59
+ throw new ExternalException ( "Open Service Error" ) ;
60
+ }
61
+
62
+ var result = ChangeServiceConfig (
63
+ serviceHandle ,
64
+ ServiceNoChange ,
65
+ ( uint ) mode ,
66
+ ServiceNoChange ,
67
+ null ,
68
+ null ,
69
+ IntPtr . Zero ,
70
+ null ,
71
+ null ,
72
+ null ,
73
+ null ) ;
74
+
75
+ if ( result == false )
76
+ {
77
+ var nError = Marshal . GetLastWin32Error ( ) ;
78
+ var win32Exception = new Win32Exception ( nError ) ;
79
+ throw new ExternalException ( "Could not change service start type: "
80
+ + win32Exception . Message ) ;
81
+ }
82
+
83
+ CloseServiceHandle ( serviceHandle ) ;
84
+ CloseServiceHandle ( scManagerHandle ) ;
85
+ }
86
+ }
0 commit comments