Delphi: make a ServiceDelete function

I would like to make a service removal function.

Function ServiceDelete(sMachine, sService: String): Boolean;
Var
  schm, schs: SC_Handle;
  ss: TServiceStatus;
  dwChkP: dword;
Begin
  Result := False;
  schm := OpenSCManager(PChar(sMachine), Nil, SC_MANAGER_CONNECT);
  If schm > 0 Then Begin
    schs := OpenService(schm, PChar(sService), SERVICE_STOP Or SERVICE_QUERY_STATUS);
    If schs > 0 Then Begin
      If (QueryServiceStatus(schs, ss)) Then Begin
        While (SERVICE_STOPPED <> ss.dwCurrentState) Do Begin
          ControlService(schs, SERVICE_CONTROL_STOP, ss);
          dwChkP := ss.dwCheckPoint;
          Sleep(ss.dwWaitHint);
          If (Not QueryServiceStatus(schs, ss)) Then
            Break;
          If (ss.dwCheckPoint < dwChkP) Then
            Break;
        End;
      End;
      DeleteService(schs);
      CloseServiceHandle(schs);
    End;
    CloseServiceHandle(schm);

    // If service does not exist, then everything is fine.
    schm := OpenSCManager(PChar(sMachine), Nil, SC_MANAGER_CONNECT);
    If schm > 0 Then Begin
      schs := OpenService(schm, PChar(sService), SERVICE_QUERY_STATUS);
      If schs = 0 Then Begin
        If GetLastError = ERROR_SERVICE_DOES_NOT_EXIST Then
          Result := True;
      End Else Begin
        CloseServiceHandle(schs);
      End;
      CloseServiceHandle(schm);
    End;
  End;
End;

It opens the service manager, opens the service, executes DeleteService, but does not delete the service. The function returns false, and the service still exists. What am I doing wrong?

+4
source share
1 answer

According to DeleteService and Security and Permission Service , you need to add STANDARD_RIGHTS_REQUIRED = $F0000;to receive

schs := OpenService(schm, PChar(sService), STANDARD_RIGHTS_REQUIRED  or SERVICE_STOP Or SERVICE_QUERY_STATUS);

In addition, it is important to run the program with administrator rights and check the result of each function in the order, as indicated in the comments.

EDIT:

Remy Lebeau, , Winapi.Windows._DELETE = $00010000;,

schs := OpenService(schm, PChar(sService), Winapi.Windows._DELETE or SERVICE_STOP Or SERVICE_QUERY_STATUS);
+4

Source: https://habr.com/ru/post/1620556/


All Articles