Click to Rate and Give Feedback
MSDN
MSDN Library
Sending Control Requests to a Service

The following example uses the ControlService function to send a control value to a running service. Different control values require different levels of access to the service object. For example, a service object handle must have SERVICE_STOP access to send the SERVICE_CONTROL_STOP control code. When ControlService returns, a SERVICE_STATUS structure contains the latest status information for the service.

#include <windows.h>
#include <stdio.h>

SC_HANDLE schService;
SC_HANDLE schSCManager;

BOOL ControlSampleService(DWORD fdwControl) 
{ 
    SERVICE_STATUS ssStatus; 
    DWORD fdwAccess; 
    DWORD dwStartTickCount, dwWaitTime;
 
    // The required service object access depends on the control. 
 
    switch (fdwControl) 
    { 
        case SERVICE_CONTROL_STOP: 
            fdwAccess = SERVICE_STOP; 
            break; 
 
        case SERVICE_CONTROL_PAUSE: 
        case SERVICE_CONTROL_CONTINUE: 
            fdwAccess = SERVICE_PAUSE_CONTINUE; 
            break; 
 
        case SERVICE_CONTROL_INTERROGATE: 
            fdwAccess = SERVICE_INTERROGATE; 
            break; 
 
        default: 
            fdwAccess = SERVICE_INTERROGATE; 
    } 
 
    // Open a handle to the service. 
 
    schService = OpenService( 
        schSCManager,        // SCManager database 
        TEXT("Sample_Srv"),  // name of service 
        fdwAccess);          // specify access 
    if (schService == NULL) 
    {
        printf("OpenService failed (%d)\n", GetLastError()); 
        return FALSE;
    }
 
    // Send a control value to the service. 
 
    if (! ControlService( 
            schService,   // handle to service 
            fdwControl,   // control value to send 
            &ssStatus) )  // address of status info 
    {
        printf("ControlService failed (%d)\n", GetLastError()); 
        return FALSE;
    }
 
    // Print the service status. 
 
    printf("\nStatus of Sample_Srv: \n");
    printf("  Service Type: 0x%x\n", ssStatus.dwServiceType); 
    printf("  Current State: 0x%x\n", ssStatus.dwCurrentState); 
    printf("  Controls Accepted: 0x%x\n", 
        ssStatus.dwControlsAccepted); 
    printf("  Exit Code: %d\n", ssStatus.dwWin32ExitCode); 
    printf("  Service Specific Exit Code: %d\n", 
        ssStatus.dwServiceSpecificExitCode); 
    printf("  Check Point: %d\n", ssStatus.dwCheckPoint); 
    printf("  Wait Hint: %d\n", ssStatus.dwWaitHint); 
 
    return TRUE; 
}
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker