How can I disable a service via Delphi?

You can use file JclSvcCtrl.pas from JEDI Components Library (JCL). I have written a pseudo example that you could use. However, be aware that I didn't test it. But in this way it should work (error checks omitted):

M := TJclSCManager.Create;
M.Refresh(true);  //Not sure if true is needed or not (refresh all services)
For i := 0 to M.ServiceCount -1 do
begin
  S := M.Services[i]; //TJclNtService
  if CompareText(S.ServiceName, 'bla') then
  begin
    S.Stop;
    S.StartType := sstDisabled;   
    S.Commit;
    break;
  end;
end;

Open the service with OpenService, and then disable it by passing Service_Disabled as the dwStartType parameter for ChangeServiceConfig. Specify a null pointer or Service_No_Change for the rest of the parameters since you're not interested in changing them.


Besides using the previous methods, if you need more control you can use WMI.
With Win32_Service class have access to all information of the services installed on the machine and you can has access to methods: Start, Stop, Pause, Resume, Interrogate, Create, Delete, Change, ChangeStartMode...

Here (Web / SourceForge)you can find a set of components to work with WMI (GLibWMI components Library); There are one called CServiceInfo thah give you all information and some methods of this class.

In addition with the package tere are some demos; One is called (ServiceControl) and implement all methods.

alt text

All the package are source included. See the code it can be usefull for you.

Regards.

Tags:

Delphi

Service