Every good software package supports uninstall just as well as it supports install. So you'll need to know how to remove a service too. To remove a service, you must first open it:
SC_HANDLE OpenService( SC_HANDLE hSCManager, PCTSTR pszInternalName, DWORD dwDesiredAccess); |
To the OpenService function, you pass the handle returned from OpenSCManager, followed by the internal name of the service (the same value that you passed in CreateService's pszServiceName parameter), and then DELETE for the desired access. Now that you have the handle to the specific service, you can delete the service by calling DeleteService, passing the handle returned from OpenService:
BOOL DeleteService(SC_HANDLE hService); |
DeleteService does not actually delete the service right away; it simply marks the service for deletion. The SCM will delete the service only when the service stops running and after all open handles to the service have been closed.
I also write my service executables so that they can delete their services from the SCM's database. If "-remove" is passed as a command-line argument, I call a function such as ServiceRemove, shown here:
void ServiceRemove(PCTSTR pszInternalName) { // Open the SCM database SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT); // Open the service for delete access SC_HANDLE hService = OpenService(hSCM, pszInternalName, DELETE); // Mark the service for deletion // NOTE: The service is not deleted until all handles // to it are closed and the service stops running DeleteService(hService); // Close the service and the SCM CloseServiceHandle(hService); CloseServiceHandle(hSCM); } |
NOTE
For clarity, the preceding code does not have any error checking. OpenSCManager, OpenService, and DeleteService can fail for many reasons. Please add the proper error checking when adding code like this into your own application.