RegisterServiceCtrlHandler

  SERVICE_STATUS_HANDLE RegisterServiceCtrlHandler(lpServiceName, lpHandlerProc)    
  LPTSTR lpServiceName;    
  LPHANDLER_FUNCTION lpHandlerProc;    

The RegisterServiceCtrlHandler function registers function to handle service control requests for a service.

Parameters

lpServiceName

Name of the service run by the current thread.

lpHandlerProc

Pointer to the service control handling function can be of any name with this prototype:

VOID HandlerFunction(DWORD dwControl);

Where dwControl indicates the requested control, as shown in the following list:

Value Meaning

SERVICE_CONTROL_STOP  
  requests the service to stop.
SERVICE_CONTROL_PAUSE  
  requests the service to pause.
SERVICE_CONTROL_CONTINUE  
  requests the paused service to resume.
SERVICE_CONTROL_INTERROGATE  
  requests that the service updates the Service Control Manager of its status information immediately.

Return Value

Returns a handle for subsequent calls to SetServiceStatus API to update the Service Control Manager of this service's status information. This handle does not have to be closed because it does not contain any context information.

If return value is NULL, an error has occurred. Use GetLastError to determine the cause of the failure.

Errors Value Meaning
  ERROR_INVALID_NAME The specified service name is invalid.
  ERROR_SERVICE_DOES_NOT_EXIST The specified service does not exist.

Comments

The new service thread running ServiceMainFunction should immediately call RegisterServiceCtrlHandler to register a control handling function with the control dispatcher. This so that the control dispatcher can call this routine to field control requests on this service's behalf.

This function must be called before the first SetServiceStatus call because it returns a service status handle for the caller to use, so that no other service can inadvertently set this service's status maintained by the Service Control Manager. It also needs to be called before the first SetServiceStatus so that a control handler is in place to field control requests by the time the service specifies the controls it accepts via SetServiceStatus.

When the control handler is invoked with a control request, the service must notify the Service Control Manager of its latest status by calling SetServiceStatus within the context of the control handler. The service is required to call SetServiceStatus whether the status of the service has changed or not in response to the control request.