Services API Reference
Introduction
The Services API provides functions to install, configure, start, stop, and query Windows services. All functions are declared in winsvc.h and linked against Advapi32.lib.
Table of Contents
CreateService
Creates a service object and adds it to the specified service control manager database.
#include <windows.h>
#include <winsvc.h>
SC_HANDLE hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
if (hSCM) {
SC_HANDLE hService = CreateService(
hSCM,
L"MyService",
L"My Sample Service",
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
L"C:\\Path\\MyService.exe",
NULL,
NULL,
NULL,
NULL,
NULL);
// check hService for success
CloseServiceHandle(hService);
}
CloseServiceHandle(hSCM);
| Parameter | Description |
|---|---|
hSCM | Handle to the service control manager. |
lpServiceName | Internal name of the service. |
lpDisplayName | Friendly name displayed in MMC. |
dwDesiredAccess | Access rights for the service. |
dwServiceType | Type of service (e.g., SERVICE_WIN32_OWN_PROCESS). |
dwStartType | Startup option (SERVICE_DEMAND_START or SERVICE_AUTO_START). |
dwErrorControl | Severity of errors if service fails. |
DeleteService
Marks a service for deletion. The service is removed after all handles to it are closed.
SC_HANDLE hService = OpenService(hSCM, L"MyService", DELETE);
if (hService) {
DeleteService(hService);
CloseServiceHandle(hService);
}
StartService
Starts a service that is in a stopped state.
SC_HANDLE hService = OpenService(hSCM, L"MyService", SERVICE_START);
if (hService) {
StartService(hService, 0, NULL);
CloseServiceHandle(hService);
}
ControlService
Sends a control code to a service (e.g., stop, pause).
SERVICE_STATUS status;
SC_HANDLE hService = OpenService(hSCM, L"MyService", SERVICE_STOP);
if (hService) {
ControlService(hService, SERVICE_CONTROL_STOP, &status);
CloseServiceHandle(hService);
}
QueryServiceStatusEx
Retrieves detailed status information for a service.
SERVICE_STATUS_PROCESS ssp;
DWORD bytesNeeded;
SC_HANDLE hService = OpenService(hSCM, L"MyService", SERVICE_QUERY_STATUS);
if (hService) {
QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO,
(LPBYTE)&ssp, sizeof(ssp), &bytesNeeded);
// ssp.dwCurrentState contains the state
CloseServiceHandle(hService);
}
EnumServicesStatusEx
Enumerates services in the specified service control manager database.
DWORD dwBytesNeeded, dwServicesReturned, dwResumeHandle = 0;
EnumServicesStatusEx(
hSCM,
SC_ENUM_PROCESS_INFO,
SERVICE_WIN32,
SERVICE_STATE_ALL,
NULL,
0,
&dwBytesNeeded,
&dwServicesReturned,
&dwResumeHandle,
NULL);
BYTE* buffer = new BYTE[dwBytesNeeded];
EnumServicesStatusEx(
hSCM,
SC_ENUM_PROCESS_INFO,
SERVICE_WIN32,
SERVICE_STATE_ALL,
buffer,
dwBytesNeeded,
&dwBytesNeeded,
&dwServicesReturned,
&dwResumeHandle,
NULL);