1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
|
{
$Id: header,v 1.1 2000/07/13 06:33:45 michael Exp $
This file is part of the Free Component Library (FCL)
Copyright (c) 1999-2000 by the Free Pascal development team
See the file COPYING.FPC, included in this distribution,
for details about the copyright.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
**********************************************************************}
{$mode objfpc}
{$h+}
unit ServiceManager;
interface
uses
Windows, SysUtils, Classes, jwawinnt, jwawinsvc;
type
TServiceEntry = Class(TCollectionItem)
Private
FServiceName,
FDisplayName : String;
FServiceType,
FCurrentState,
FControlsAccepted,
FWin32ExitCode,
FServiceSpecificExitCode,
FCheckPoint,
FWaitHint: DWORD;
Private
Procedure SetStatusFields(Const Status : TServiceStatus);
Public
Property ServiceName : String Read FServiceName;
Property DisplayName : String read FDIsplayName;
Property ServiceType : DWord Read FServiceType;
Property CurrentState : DWord Read FCurrentState;
Property ControlsAccepted : DWord Read FControlsAccepted;
Property Win32ExitCode : DWord Read FWin32ExitCode;
Property ServiceSpecificExitCode : DWord Read FServiceSpecificExitCode;
Property CheckPoint : DWord Read FCheckPoint;
Property WaitHint: DWORD Read FWaitHint;
end;
TServiceEntries = Class(TOwnedCollection)
Private
Function GetService (Index : Integer) : TServiceEntry;
Public
Function FindService(ServiceName : String) : TServiceEntry;
Function ServiceByName(ServiceName : String) : TServiceEntry;
Property Items [index : Integer] : TServiceEntry Read GetService;default;
end;
{ Record used in
registerservice,
configservice or
queryserviceconfig
}
TServiceDescriptor = Record
Name : ShortString;
DisplayName : ShortString;
DesiredAccess : DWord;
ServiceType : DWord;
StartType : DWord;
ErrorControl : DWord;
CommandLine : String;
LoadOrderGroup : String;
TagID : DWord;
Dependencies : String; // Separated by slash signs (/)
UserName : String;
Password : String;
end;
TServiceManager = class(TComponent)
private
{ Private declarations }
FReconnect : Boolean;
FMachineName : String;
FAccess : DWord;
FHandle : THandle;
FDBLock : SC_LOCK;
FServices : TServiceEntries;
FAfterRefresh : TNotifyEvent;
FAfterConnect: TNotifyEvent;
FRefreshOnConnect: Boolean;
FBeforeDisConnect: TNotifyEvent;
function GetConnected: Boolean;
procedure SetConnected(const Value: Boolean);
procedure SetMachineName(const Value: string);
protected
{ Protected declarations }
procedure Loaded;override;
Procedure SMError(Msg : String);
Procedure CheckConnected(Msg : String);
Procedure DoBeforeDisConnect; virtual;
Procedure DoAfterConnect; virtual;
Procedure DoAfterRefresh; virtual;
public
{ Public declarations }
Constructor Create(AOwner: TComponent); override;
Destructor Destroy; override;
Procedure ClearServices;
Procedure Refresh;
Procedure Connect;
Procedure Disconnect;
function GetServiceHandle(ServiceName: String; SAccess: DWord): THandle;
procedure ContinueService(SHandle: THandle); overload;
procedure ContinueService(ServiceName : String); overload;
procedure StartService(SHandle: THandle; Args: TStrings);overload;
procedure StartService(ServiceName : String; Args: TStrings); overload;
procedure StopService(ServiceName: String; StopDependent: Boolean); overload;
procedure StopService(SHandle : THandle; StopDependent: Boolean); overload;
procedure PauseService(SHandle: THandle);overload;
procedure PauseService(ServiceName: String);Overload;
procedure CustomControlService(ServiceName : String; ControlCode : DWord); overload;
procedure CustomControlService(Shandle : THandle; ControlCode : DWord); overload;
procedure ListDependentServices(SHandle: THandle; ServiceState: DWord; List: TStrings); overload;
procedure ListDependentServices(ServiceName : String; ServiceState : DWord; List : TStrings); overload;
Procedure LockServiceDatabase;
Procedure UnlockServiceDatabase;
procedure QueryServiceConfig(SHandle : THandle; Var Config : TServiceDescriptor);overload;
procedure QueryServiceConfig(ServiceName : String; Var Config : TServiceDescriptor);overload;
Function RegisterService(Var Desc : TServiceDescriptor) : THandle;
procedure SetStartupType(ServiceName: String; StartupType: DWord); overload;
procedure SetStartupType(SHandle : THandle; StartupType: DWord); overload;
Procedure UnregisterService(ServiceName : String);
procedure ConfigService(SHandle: THandle; Config: TServiceDescriptor); overload;
procedure ConfigService(ServiceName : string; Config: TServiceDescriptor); overload;
procedure RefreshServiceStatus(ServiceName: String);
procedure GetServiceStatus(SHandle : THandle; Var Status : TServiceStatus); overload;
procedure GetServiceStatus(ServiceName : String; Var Status : TServiceStatus); overload;
Property Handle : THandle Read FHandle;
Property Acces : DWord read FAccess Write FAccess;
Property Services : TServiceEntries Read FServices;
published
{ Published declarations }
Property Connected : Boolean Read GetConnected Write SetConnected;
Property MachineName : string Read FMachineName Write SetMachineName;
Property RefreshOnConnect : Boolean Read FRefreshOnConnect Write FrefreshOnConnect;
Property AfterRefresh : TNotifyEvent Read FAfterRefresh Write FAfterRefresh;
Property AfterConnect : TNotifyEvent Read FAfterConnect Write FAfterConnect;
Property BeforeDisConnect : TNotifyEvent Read FBeforeDisConnect Write FBeforeDisConnect;
end;
EServiceManager = Class(Exception);
Const
StartTypes : Array[0..4] of DWord = (
SERVICE_AUTO_START,SERVICE_BOOT_START, SERVICE_DEMAND_START,
SERVICE_SYSTEM_START, SERVICE_DISABLED );
ServiceTypes : Array[0..3] of DWord = (
SERVICE_FILE_SYSTEM_DRIVER, SERVICE_KERNEL_DRIVER,
SERVICE_WIN32_OWN_PROCESS, SERVICE_WIN32_SHARE_PROCESS );
StartErrors : Array[0..3] of DWord = (
SERVICE_ERROR_IGNORE, SERVICE_ERROR_NORMAL,
SERVICE_ERROR_SEVERE, SERVICE_ERROR_CRITICAL);
Function ServiceTypeToString(AType : Dword) : String;
Function ServiceStateToString(AState : DWord) : String;
Function ControlsAcceptedToString(AValue : DWord) : String;
Function IsInteractiveService(AType : Dword) : Boolean;
implementation
ResourceString
SErrConnected = 'Operation not permitted while connected to Service Control Manager';
SErrNotConnected = 'Not connected to Service control manager. Cannot %s';
SErrInvalidControlCode = 'Invalid custom control code : %d';
SQueryServiceList = 'Query service list';
SActive = 'Active';
SInactive = 'Inactive';
SStopped = 'Stopped';
SStartPending = 'Start pending';
SStopPending = 'Stop pending';
SRunning = 'Running';
SContinuePending = 'Continue pending';
SPausePending = 'Pause pending';
SPaused = 'Paused';
SUnknownState = 'Unknown State (%d)';
SUnknownType = 'Unknown type (%d)';
SStop = 'Stop';
SPauseContinue = 'Pause/continue';
SShutDown = 'Shutdown';
SDeviceDriver = 'Device driver';
SFileSystemDriver = 'Filesystem driver';
SAdapter = 'Adapter';
SRecognizer = 'Recognizer';
SService = 'Service';
SSHaredService = 'Service (shared)';
SErrServiceNotFound = 'Service "%s" not found.';
{ TServiceManager }
{$ifdef ver130}
Type
PCharArray = Array[Word] of PChar;
PPCharArray = ^PCharArray;
Procedure RaiseLastOSError;
begin
RaiseLastWin32Error;
end;
{$endif}
procedure TServiceManager.CheckConnected(Msg: String);
begin
If Not Connected then
SMError(Format(SErrNotConnected,[Msg]));
end;
procedure TServiceManager.ClearServices;
begin
FServices.Clear;
end;
procedure TServiceManager.Connect;
Var
P : PChar;
begin
If (FHandle=0) then
begin
P:=Nil;
If (MachineName<>'') then
P:=PChar(MachineName);
FHandle:=OpenSCManager(P,Nil,FAccess);
If (FHandle=0) then
RaiseLastOSError;
DoAfterConnect;
If RefreshOnConnect then
Refresh;
end;
end;
constructor TServiceManager.Create(AOwner: TComponent);
begin
inherited;
FServices:=TServiceEntries.Create(Self,TServiceEntry);
FAccess:=SC_MANAGER_ALL_ACCESS;
end;
destructor TServiceManager.Destroy;
begin
FServices.Free;
Inherited;
end;
procedure TServiceManager.Disconnect;
begin
IF (FHandle<>0) then
begin
DoBeforeDisConnect;
CloseServiceHandle(FHandle);
FHandle:=0;
end;
end;
function TServiceManager.GetConnected: Boolean;
begin
Result:=(Handle<>0);
end;
procedure TServiceManager.Refresh;
Var
BytesNeeded,
ServicesReturned,
ResumeHandle : DWord;
Info,P : PEnumServiceStatus;
E : TServiceEntry;
I : integer;
begin
ClearServices;
CheckConnected(SQueryServiceList);
BytesNeeded:=0;
ServicesReturned:=0;
ResumeHandle:=0;
Info:=Nil;
EnumServicesStatus(FHandle,SERVICE_WIN32,SERVICE_STATE_ALL,Info,0,
BytesNeeded,ServicesReturned,Resumehandle);
if (GetLastError<>ERROR_MORE_DATA) then
RaiseLastOSError;
Getmem(Info,BytesNeeded);
Try
P:=Info;
If Not EnumServicesStatus(FHandle,SERVICE_WIN32,SERVICE_STATE_ALL,Info,BytesNeeded,
BytesNeeded,ServicesReturned,Resumehandle) then
RaiseLastOSError;
For I:=1 to Servicesreturned do
begin
E:=FServices.Add as TServiceEntry;
With E,P^ do
begin
FServiceName:=StrPas(lpServiceName);
FDisplayName:=StrPas(lpDisplayName);
SetStatusFields(ServiceStatus);
end;
PChar(P):=Pchar(P)+SizeOf(TEnumServiceStatus);
end;
Finally
FreeMem(Info);
end;
DoAfterRefresh;
end;
procedure TServiceManager.SetConnected(const Value: Boolean);
begin
If (([csLoading,csdesigning] * ComponentState)<>[]) then
FReconnect:=Value
else
If Value<>GetConnected then
If Value then
Connect
Else
Disconnect;
end;
procedure TServiceManager.Loaded;
begin
Inherited;
If FReconnect then
Connect;
end;
procedure TServiceManager.SetMachineName(const Value: string);
begin
If Connected then
SMError(SErrConnected);
FMachineName := Value;
end;
procedure TServiceManager.SMError(Msg: String);
begin
raise EServiceManager.Create(Msg);
end;
Function ServiceTypeToString(AType : Dword) : String;
begin
Case (AType and $FF) of
SERVICE_KERNEL_DRIVER : Result:=SDeviceDriver;
SERVICE_FILE_SYSTEM_DRIVER : Result:=SFileSystemDriver;
SERVICE_ADAPTER : Result:=SAdapter;
SERVICE_RECOGNIZER_DRIVER : Result:=SRecognizer;
SERVICE_WIN32_OWN_PROCESS : Result:=SService;
SERVICE_WIN32_SHARE_PROCESS : Result:=SSHaredService;
else
Result:=Format(SUnknownType,[AType]);
end;
end;
Function IsInteractiveService(AType : Dword) : Boolean;
begin
Result:=(Atype and SERVICE_INTERACTIVE_PROCESS)<>0;
end;
Function ServiceStateToString(AState : Dword) : String;
begin
Case AState of
SERVICE_STOPPED : Result:=SStopped;
SERVICE_START_PENDING : Result:=SStartPending;
SERVICE_STOP_PENDING : Result:=SStopPending;
SERVICE_RUNNING : Result:=SRunning;
SERVICE_CONTINUE_PENDING : Result:=SContinuePending;
SERVICE_PAUSE_PENDING : Result:=SPausePending;
SERVICE_PAUSED : Result:=SPaused;
else
Result:=Format(SUnknownState,[AState]);
end;
end;
Function ControlsAcceptedToString(AValue : DWord) : String;
Procedure AddToResult(S : String);
begin
If (Result='') then
Result:=S
else
Result:=Result+','+S
end;
begin
Result:='';
If (AValue and SERVICE_ACCEPT_STOP)<>0 then
AddToResult(SStop);
If (AValue and SERVICE_ACCEPT_PAUSE_CONTINUE)<>0 then
AddToResult(SPauseContinue);
If (AValue and SERVICE_ACCEPT_SHUTDOWN)<>0 then
AddToResult(SShutDown)
end;
procedure TServiceManager.DoAfterConnect;
begin
If Assigned(FAfterConnect) then
FAfterConnect(Self);
end;
procedure TServiceManager.DoAfterRefresh;
begin
If Assigned(FAfterRefresh) then
FAfterRefresh(Self);
end;
procedure TServiceManager.DoBeforeDisConnect;
begin
If Assigned(FBeforeDisconnect) then
FBeforeDisconnect(Self);
end;
Function AllocDependencyList (Const S : String) : PChar;
Var
I,L : Integer;
begin
Result:=Nil;
If (S<>'') then
begin
// Double Null terminated list of null-terminated strings.
L:=Length(S);
GetMem(Result,L+3);
Move(S[1],Result^,L+1); // Move terminating null as well.
Result[L+1]:=#0;
Result[L+2]:=#0;
For I:=0 to L-1 do
If Result[i]='/' then // Change / to #0.
Result[i]:=#0;
end;
end;
Function TServiceManager.RegisterService(var Desc: TServiceDescriptor) : Thandle;
Var
PDep,PLO,PUser,PPWd : PChar; // We need Nil for some things.
N,D : String;
ReturnTag : DWord;
begin
With Desc do
begin
N:=Name;
D:=DisplayName;
If (LoadOrderGroup='') then
PLO:=Nil
else
PLO:=PChar(LoadOrderGroup);
PPwd:=Nil;
PUser:=Nil;
If (UserName<>'') then
begin
PUser:=PChar(UserName);
If (Password<>'') then
PPWd:=PChar(Password);
end;
PDep:=AllocDependencyList(Dependencies);
Try
Result:=CreateService(Self.Handle,PChar(N),PChar(D),DesiredAccess,ServiceType,
StartType,ErrorControl,PChar(CommandLine),PLO,Nil,
PDep,PUser,PPwd);
If (Result=0) then
RaiseLastOSError;
Finally
If PDep<>Nil then
FreeMem(PDep);
end;
end;
end;
procedure TServiceManager.ListDependentServices(ServiceName : String; ServiceState : DWord; List : TStrings);
Var
H : THandle;
begin
H:=OpenService(Handle,PChar(ServiceName),SERVICE_ENUMERATE_DEPENDENTS);
try
ListDependentServices(H,ServiceState,List);
Finally
CloseServiceHandle(H);
end;
end;
procedure TServiceManager.ListDependentServices(SHandle: THandle; ServiceState : DWord; List : TStrings);
Var
P,E : PEnumServiceStatus;
I,BytesNeeded,Count : DWord;
begin
P:=Nil;
List.Clear;
// If call succeeds with size 0, then there are no dependent services...
if Not EnumDependentServices(SHandle,ServiceState,P,0,BytesNeeded,Count) then
begin
If (GetLastError<>ERROR_MORE_DATA) then
RaiseLastOSError;
GetMem(P,BytesNeeded);
Try
If Not EnumDependentServices(SHandle,ServiceState,P,bytesNeeded,BytesNeeded,Count) Then
RaiseLastOSError;
E:=P;
For I:=0 to Count-1 do
begin
List.Add(StrPas(E^.lpServiceName));
Pchar(E):=PChar(E)+SizeOf(TEnumServiceStatus);
end;
Finally
FreeMem(P);
end;
end;
end;
Procedure TServiceManager.StopService(SHandle : THandle; StopDependent : Boolean);
Var
I : Integer;
List : TStrings;
Status : TServiceStatus;
begin
If Not QueryServiceStatus(SHandle,Status) then
RaiseLastOSError;
If Not (Status.dwCurrentState=SERVICE_STOPPED) then
begin
If StopDependent then
begin
List:=TStringList.Create;
Try
ListDependentServices(SHandle,SERVICE_ACTIVE,List);
For I:=0 to List.Count-1 do
StopService(List[i],False); // Do not recurse !!
Finally
List.Free;
end;
end;
If Not ControlService(SHandle,SERVICE_CONTROL_STOP,Status) then
RaiseLastOSError;
end;
end;
Procedure TServiceManager.StopService(ServiceName : String; StopDependent : Boolean);
Var
H : THandle;
A : DWORD;
begin
A:=SERVICE_STOP or SERVICE_QUERY_STATUS;
If StopDependent then
A:=A or SERVICE_ENUMERATE_DEPENDENTS;
H:=OpenService(Handle,PChar(ServiceName),A);
Try
StopService(H,StopDependent);
Finally
CloseServiceHandle(H);
end;
end;
Function TServiceManager.GetServiceHandle(ServiceName : String; SAccess : DWord) : THandle;
begin
Result:=OpenService(Handle,PChar(ServiceName),SAccess);
If (Result=0) then
RaiseLastOSError;
end;
procedure TServiceManager.UnregisterService(ServiceName: String);
Var
H : THandle;
Status : TServiceStatus;
begin
StopService(ServiceName,True);
H:=GetServiceHandle(ServiceName,SERVICE_STOP or SERVICE_QUERY_STATUS or SERVICE_DELETE);
Try
If Not DeleteService(H) then
RaiseLastOSError;
Finally
CloseServiceHandle(H);
end;
end;
Procedure TServiceManager.PauseService(SHandle : THandle);
Var
Status : TServiceStatus;
begin
If Not ControlService(SHandle,SERVICE_CONTROL_PAUSE,Status) then
RaiseLastOSError;
end;
Procedure TServiceManager.PauseService(ServiceName : String);
Var
H : THandle;
begin
H:=GetServiceHandle(ServiceName,SERVICE_PAUSE_CONTINUE);
Try
PauseService(H);
Finally
CloseServiceHandle(H);
end;
end;
Procedure TServiceManager.ContinueService(SHandle : THandle);
Var
Status : TServiceStatus;
begin
If Not ControlService(SHandle,SERVICE_CONTROL_CONTINUE,Status) then
RaiseLastOSError;
end;
Procedure TServiceManager.ContinueService(ServiceName : String);
Var
H : THandle;
begin
H:=GetServiceHandle(ServiceName,SERVICE_PAUSE_CONTINUE);
Try
ContinueService(H);
Finally
CloseServiceHandle(H);
end;
end;
Function StringsToPCharList(List : TStrings) : PPChar;
Var
I : Integer;
S : String;
begin
I:=(List.Count)+1;
GetMem(Result,I*sizeOf(PChar));
PPCharArray(Result)^[List.Count]:=Nil;
For I:=0 to List.Count-1 do
begin
S:=List[i];
PPCharArray(Result)^[i]:=StrNew(PChar(S));
end;
end;
Procedure FreePCharList(List : PPChar);
Var
I : integer;
begin
I:=0;
While PPChar(List)[i]<>Nil do
begin
StrDispose(PPChar(List)[i]);
Inc(I);
end;
FreeMem(List);
end;
Procedure TServiceManager.StartService(SHandle : THandle; Args : TStrings);
Var
Argc : DWord;
PArgs : PPchar;
begin
If (Args=Nil) or (Args.Count>0) then
begin
Argc:=0;
Pargs:=Nil;
end
else
begin
ArgC:=Args.Count;
Pargs:=StringsToPcharList(Args);
end;
Try
If not jwawinsvc.StartService(SHandle,Argc,PArgs^) then
RaiseLastOSError;
Finally
If (PArgs<>Nil) then
FreePCharList(PArgs);
end;
end;
Procedure TServiceManager.StartService(ServiceName : String; Args : TStrings);
Var
H : THandle;
begin
H:=GetServiceHandle(ServiceName,SERVICE_START);
Try
StartService(H,Args);
Finally
CloseServiceHandle(H);
end;
end;
Procedure TServiceManager.LockServiceDatabase;
begin
FDBLock:=jwawinsvc.LockServiceDatabase(Handle);
If FDBLock=Nil then
RaiseLastOSError;
end;
procedure TServiceManager.UnlockServiceDatabase;
begin
If (FDBLock<>Nil) then
begin
Try
If Not jwawinsvc.UnLockServiceDatabase(FDBLock) then
RaiseLastOSError;
Finally
FDBLock:=Nil;
end;
end;
end;
procedure TServiceManager.QueryServiceConfig(SHandle : THandle; Var Config : TServiceDescriptor);
Var
SvcCfg : PQueryServiceConfig;
BytesNeeded : DWord;
begin
jwawinsvc.QueryServiceConfig(SHandle,Nil,0,BytesNeeded);
If (GetLastError<>ERROR_INSUFFICIENT_BUFFER) then
RaiseLastOSError;
GetMem(SvcCfg,BytesNeeded);
Try
If Not jwawinsvc.QueryServiceConfig(SHandle,SvcCfg,BytesNeeded,BytesNeeded) then
RaiseLastOSError;
With config,SvcCfg^ do
begin
Password:='';
Name:='';
DesiredAccess:=0;
ErrorControl:=dwErrorControl;
ServiceType:=dwServiceType;
StartType:=dwStartType;
TagID:=dwTagID;
CommandLine:=lpBinaryPathName;
LoadOrderGroup:=lpLoadOrderGroup;
Dependencies:=lpDependencies;
UserName:=lpServiceStartName;
DisplayName:=lpDisplayName;
end;
Finally
FreeMem(SvcCfg,BytesNeeded);
end;
end;
procedure TServiceManager.QueryServiceConfig(ServiceName : String; Var Config : TServiceDescriptor);
Var
H : THandle;
begin
H:=GetServiceHandle(ServiceName,SERVICE_QUERY_CONFIG);
Try
QueryServiceConfig(H,Config);
Finally
CloseServiceHandle(H);
end;
end;
procedure TServiceManager.SetStartupType(ServiceName : String; StartupType : DWord);
Var
H : THandle;
begin
H:=GetServiceHandle(ServiceName,SERVICE_CHANGE_CONFIG);
Try
SetStartupType(H,StartupType);
Finally
CloseServiceHandle(H);
end;
end;
procedure TServiceManager.SetStartupType(SHandle : THandle; StartupType: DWord);
Const
SNC = SERVICE_NO_CHANGE; // Shortcut
begin
If Not ChangeServiceConfig(SHandle,SNC,StartupType,SNC,Nil,Nil,Nil,Nil,Nil,Nil,Nil) then
RaiseLastOSError;
end;
procedure TServiceManager.ConfigService(SHandle : THandle ; Config : TServiceDescriptor);
Function SToPchar(Var S : String) : PChar;
begin
If (S='') then
Result:=Nil
else
Result:=PChar(S);
end;
Var
PDep,PLO,PUser,PPWd,PCmd,PDisp : PChar; // We need Nil for some things.
D : String;
ReturnTag : DWord;
begin
With Config do
begin
PCmd:=SToPChar(CommandLine);
D:=DisplayName;
PDisp:=StoPChar(D);
PLO:=SToPChar(LoadOrderGroup);
PUser:=SToPChar(UserName);
PPwd:=SToPchar(Password);
PDep:=AllocDependencyList(Dependencies);
Try
If Not ChangeServiceConfig(SHandle,ServiceType,StartType,ErrorControl,
PCmd,PLO,Nil,PDep,PUser,PPwd,PDisp) then
RaiseLastOSError;
Finally
If PDep<>Nil then
FreeMem(PDep);
end;
end;
end;
procedure TServiceManager.GetServiceStatus(SHandle : THandle; Var Status: TServiceStatus);
begin
If Not QueryServiceStatus(SHandle,Status) then
RaiseLastOSError;
end;
procedure TServiceManager.GetServiceStatus(ServiceName : String; Var Status: TServiceStatus);
Var
H : THandle;
begin
H:=GetServiceHandle(ServiceName,SERVICE_QUERY_STATUS);
Try
GetServiceStatus(H,Status);
Finally
CloseServiceHandle(H);
end;
end;
procedure TServiceManager.RefreshServiceStatus(ServiceName : String);
Var
Status : TServiceStatus;
SE : TServiceEntry;
begin
SE:=Services.ServiceByName(ServiceName);
GetServiceStatus(ServiceName,Status);
SE.SetStatusFields(Status);
end;
procedure TServiceManager.ConfigService(ServiceName : String; Config : TServiceDescriptor);
Var
H : THandle;
begin
H:=GetServiceHandle(ServiceName,SERVICE_CHANGE_CONFIG);
Try
ConfigService(H,Config);
Finally
CloseServiceHandle(H);
end;
end;
procedure TServiceManager.CustomControlService(ServiceName: String; ControlCode: DWord);
Var
H : THandle;
begin
H:=GetServiceHandle(ServiceName,SERVICE_USER_DEFINED_CONTROL);
Try
CustomControlService(H,ControlCode);
Finally
CloseServiceHandle(H);
end;
end;
procedure TServiceManager.CustomControlService(Shandle: THandle;
ControlCode: DWord);
Var
Status : TServiceStatus;
begin
If (ControlCode<128) or (ControlCode>255) then
Raise EServiceManager.CreateFmt(SErrInvalidControlCode,[ControlCode]);
If Not ControlService(SHandle,ControlCode,Status) then
RaiseLastOSError;
end;
{ TServiceEntries }
function TServiceEntries.FindService(ServiceName: String): TServiceEntry;
Var
I : Integer;
begin
Result:=Nil;
I:=Count-1;
While (I>=0) and (Result=Nil) do
If CompareText(Items[i].ServiceName,ServiceName)=0 then
Result:=Items[i]
else
Dec(I);
end;
function TServiceEntries.GetService(Index: Integer): TServiceEntry;
begin
Result:=inherited Items[Index] as TServiceEntry;
end;
function TServiceEntries.ServiceByName(ServiceName: String): TServiceEntry;
begin
Result:=FindService(ServiceName);
If Result=Nil then
Raise EServiceManager.CreateFmt(SErrServiceNotFound,[ServiceName]);
end;
{ TServiceEntry }
procedure TServiceEntry.SetStatusFields(const Status: TServiceStatus);
begin
With Status do
begin
FServiceType:=dwServiceType;
FCurrentState:=dwCurrentState;
FControlsAccepted:=dwControlsAccepted;
FWin32ExitCode:=dwWin32ExitCode;
FServiceSpecificExitCode:=dwServiceSpecificExitCode;
FCheckPoint:=dwCheckPoint;
FWaitHint:=dwWaitHint;
end;
end;
end.
|