Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / Win32

Create a service

2.60/5 (5 votes)
15 Jan 2011CPOL 14.3K  
This tip shows how to create a service
C++
#include <windows.h>
#include <stdio.h>

BOOL CreateSampleService(LPCTSTR lpszDisplayName, LPCTSTR szPath)
{
    TCHAR szPath[MAX_PATH];

    if( !GetModuleFileName( NULL, szPath, MAX_PATH ) )
    {
        printf("GetModuleFileName failed (%d)\n", GetLastError());
        return FALSE;
    }

    schService = CreateService(
        schSCManager,              // SCManager database
        TEXT("Sample_Srv"),        // name of service
        lpszDisplayName,           // service name to display
        SERVICE_ALL_ACCESS,        // desired access
        SERVICE_WIN32_OWN_PROCESS, // service type
        SERVICE_DEMAND_START,      // start type
        SERVICE_ERROR_NORMAL,      // error control type
        szPath,                    // path to service's binary
        NULL,                      // no load ordering group
        NULL,                      // no tag identifier
        NULL,                      // no dependencies
        NULL,                      // LocalSystem account
        NULL);                     // no password

    if (schService == NULL)
    {
        printf("CreateService failed (%d)\n", GetLastError());
        return FALSE;
    }
    else
    {
        CloseServiceHandle(schService);
        return TRUE;
    }
}


To find out how to write a service, this site may come in handy:
http://www.devx.com/cplus/Article/9857

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)