How to use the TServiceManager Frederik and myself wrote? That's what I got asked a couple of time so post here kind of a how-to.
What is this class TServiceManager about?
It's just a little wrapper around some Windows API Functions we found useful to handle NT-Services. It allows you to query, start, stop, pause and enable/disable NT-Services on the local or a remote system.
How to use?
And here a few steps to use this class:
1) Download the Unit ServiceManager.pas (eg. from here) and place it in a directory listed in your search path within the Delphi IDE.
2) Use/inlcude the unit in your code:
uses
ServiceManager;
3) Make a instance of the class TServiceManager:
var
ServiceManager: TServiceManager;
begin
ServiceManager := TServiceManager.Create;
4) Connect to a system's Service-Manager:
ServiceManager.Connect; // Connects to the local Service-Manger
If you like to connect to a remote machines service manager just use the overload version of Connect(hostname).
5) Open a service connection to one of the Services from the above Service-Manager:
ServiceManager.OpenServiceConnection('W3SVC'); // Touch the IIS-Webservice
Hint: To get the name of a service you can use the systems service manager. Open the service properties dialog of the service you are interested in. The "service name" is what you need.
6) Do whatever you'd like to do with that service, like stop and start it again:
// Stoping Service if it is running
if ServiceManager.ServiceRunning then
ServiceManager.StopService();
// Restart Service if it is not running
if ServiceManager.ServiceStopped then
ServiceManager.StartService();
7) Destroy the object if you don't need it anymore:
FreeAndNil(ServiceManager);
That’s all. :-)
Complete sample:
uses
ServiceManager;
var
ServiceManager: TServiceManager;
begin
ServiceManager := TServiceManager.Create();
try
ServiceManager.Connect(); // Connects to the local Service-Manger
ServiceManager.OpenServiceConnection('W3SVC'); // Touch the IIS-Webservice
// Stoping Service if it is running
if ServiceManager.ServiceRunning then
ServiceManager.StopService();
// Restart Service if it is not running
if ServiceManager.ServiceStopped then
ServiceManager.StartService();
finally
FreeAndNil(ServiceManager);
end;
end;