简单操作Windows Service

//ServiceControl.h

#pragma once

#include <atlstr.h>
#include <WinSvc.h>
#include <string>
using namespace std;

class ServiceControl
{
public:
    ServiceControl(void);
    ~ServiceControl(void);

public:
    bool Init(const char* pServiceName, const char* pDisplayName, const char* pDescription);
    bool IsService(void);

    bool InstallService(void);
    bool UninstallService(void);
    bool StartService(void);
    bool StopService(void);

    bool GetConfig(string& strDisplayName, string& strDescription, string& strExePath, DWORD& dwStartType);
    bool SetConfig(string strDisplayName, string strDescription, string strStartType);

    DWORD GetStatus();
    string GetServiceName(void);

private:
    string m_strServiceName;
    string m_strDisplayName;
    string m_strDescription;

    SC_HANDLE m_hSCM;
    SC_HANDLE m_hService;
};

extern ServiceControl g_ctlService;

 

//ServiceControl.cpp

#include "StdAfx.h"
#include "ServiceControl.h"
#include "GlobalFunc.h"

#define SERVICE_STRING_AUTOMATIC    "automatic"
#define SERVICE_STRING_MANUAL        "manual"
#define SERVICE_STRING_DISABLED        "disabled"

ServiceControl g_ctlService;

//ServiceControl
ServiceControl::ServiceControl(void)
{
    m_strServiceName = "";
    m_strDisplayName = "";
    m_strDescription = "";
    m_hSCM = NULL;
    m_hService = NULL;
}

ServiceControl::~ServiceControl(void)
{
    m_strServiceName = "";
    m_strDisplayName = "";
    m_strDescription = "";
    if(m_hService != NULL)
    {
        ::CloseServiceHandle(m_hService);
    }
    if(m_hSCM != NULL)
    {
        ::CloseServiceHandle(m_hSCM);
    }
    m_hSCM = NULL;
    m_hService = NULL;
}

bool ServiceControl::Init(const char* pServiceName, const char* pDisplayName, const char* pDescription)
{
    m_strServiceName = string(pServiceName);
    m_strDisplayName = string(pDisplayName);
    m_strDescription = string(pDescription);

    if(m_hService != NULL)
    {
        ::CloseServiceHandle(m_hService);
        m_hService = NULL;
    }
    if(m_hSCM != NULL)
    {
        ::CloseServiceHandle(m_hSCM);
        m_hSCM = NULL;
    }

    // open service control manager.
    m_hSCM = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (m_hSCM == NULL)
    {
        printf_s("open service control manager occurred error: %d/n", GetLastError());
        return false;
    }

    m_hService = ::OpenService(m_hSCM, m_strServiceName.c_str(), SERVICE_ALL_ACCESS);
    return true;
}

bool ServiceControl::IsService()
{
    if(m_hSCM == NULL || m_hService == NULL)
        return false;
    else
        return true;
}

bool ServiceControl::InstallService()
{
    printf_s("begin install service.../n");
    printf_s("ServiceName:%s/n", m_strServiceName);
    printf_s("DisplayName:%s/n", m_strDisplayName);
    printf_s("Description:%s/n", m_strDescription);
    if(m_strServiceName == "")
    {
        printf_s("service name is empty./n");
        return false;
    }
    if(m_hService != NULL)
    {
        printf_s("service had been install./n");
        return false;
    }
    if(m_hSCM == NULL)
    {
        printf_s("service control manager is not open./n");
        return false;
    }

    // get file path.
    char szFilePath[MAX_PATH];
    GetModuleFileName(NULL, szFilePath, sizeof(szFilePath));

    // create service.
    m_hService = CreateService(m_hSCM,    // hSCManager
        m_strServiceName.c_str(),        // lpServiceName
        m_strDisplayName.c_str(),        // lpDisplayName
        SERVICE_ALL_ACCESS,                // dwDesiredAccess
        SERVICE_WIN32_OWN_PROCESS,        // dwServiceType
        SERVICE_AUTO_START,                // dwStartType
        SERVICE_ERROR_NORMAL,            // dwErrorControl
        szFilePath,                        // lpBinaryPathName
        NULL,                            // lpLoadOrderGroup
        NULL,                            // lpdwTagId
        NULL,                            // lpDependencies
        NULL,                            // lpServiceStartName
        NULL);                            // lpPassword
    if(m_hService == NULL)
    {
        printf_s("create service failed./n");
        return false;
    }

    // set service's description.
    SERVICE_DESCRIPTION desc;
    desc.lpDescription = (LPSTR)(m_strDescription.c_str());
    ::ChangeServiceConfig2(m_hService, SERVICE_CONFIG_DESCRIPTION, &desc);
    printf_s("completed installation./n");

    return true;
}

bool ServiceControl::UninstallService()
{
    printf_s("begin uninstall service.../n");
    printf_s("ServiceName:%s/n", m_strServiceName);
    if(m_strServiceName == "")
    {
        printf_s("service name is empty./n");
        return false;
    }
    if(m_hService == NULL)
    {
        printf_s("service is not exist./n");
        return false;
    }
    if(m_hSCM == NULL)
    {
        printf_s("service control manager is not open./n");
        return false;
    }

    // delete service.
    if(DeleteService(m_hService) == FALSE)
    {
        printf_s("delete service failed./n");
        return false;
    }

    CloseServiceHandle(m_hService);
    m_hService = NULL;
    printf_s("completed uninstallation./n");
    return true;
}

bool ServiceControl::StartService()
{
    if(m_hService == NULL)
    {
        return false;
    }
   
    if(::StartService(m_hService, 0, 0) == TRUE)
        return true;

    return false;
}

bool ServiceControl::StopService()
{
    if(m_hService == NULL)
    {
        return false;
    }

    SERVICE_STATUS status;
    if(::ControlService(m_hService, SERVICE_CONTROL_STOP, &status) == TRUE)
        return true;

    return false;
}

string ServiceControl::GetServiceName(void)
{
    return m_strServiceName;
}

bool ServiceControl::GetConfig(string& strDisplayName, string& strDescription, string& strExePath, DWORD& dwStartType)
{
    strDisplayName = "";
    strDescription = "";
    strExePath = "";
    dwStartType = 0;

    if(m_hService == NULL)
    {
        return false;
    }

    byte buffer[1024];
    QUERY_SERVICE_CONFIG* pConfig = (QUERY_SERVICE_CONFIG*)buffer;
    SERVICE_DESCRIPTION* pDescription = (SERVICE_DESCRIPTION*)buffer;
    DWORD dwBytesNeeded = 0;
    if(::QueryServiceConfig(m_hService, pConfig, sizeof(buffer), &dwBytesNeeded) == FALSE)
    {
        return false;
    }

    m_strDisplayName = pConfig->lpDisplayName;
    strDisplayName = pConfig->lpDisplayName;
    strExePath = pConfig->lpBinaryPathName;
    dwStartType = pConfig->dwStartType;

    if(::QueryServiceConfig2(m_hService, SERVICE_CONFIG_DESCRIPTION, (LPBYTE)pDescription, sizeof(buffer), &dwBytesNeeded) == FALSE)
    {
        return false;
    }

    m_strDescription = pDescription->lpDescription;
    strDescription = pDescription->lpDescription;
    return true;
}

bool ServiceControl::SetConfig(string strDisplayName, string strDescription, string strStartType)
{
    if(m_hService == NULL)
    {
        return false;
    }

    DWORD dwStartType=0;
    string_tolower(strStartType);
    if(strStartType.compare(SERVICE_STRING_AUTOMATIC) == 0)
    {
        dwStartType = SERVICE_AUTO_START;
    }
    else if(strStartType.compare(SERVICE_STRING_MANUAL) == 0)
    {
        dwStartType = SERVICE_DEMAND_START;
    }
    else if(strStartType.compare(SERVICE_STRING_DISABLED) == 0)
    {
        dwStartType = SERVICE_DISABLED;
    }
    else
    {
        dwStartType = SERVICE_AUTO_START;
    }

    if(::ChangeServiceConfig(m_hService, SERVICE_WIN32_OWN_PROCESS, dwStartType, SERVICE_ERROR_NORMAL, NULL, NULL, NULL, NULL, NULL, NULL, strDisplayName.c_str()) == FALSE)
    {
        return false;
    }

    m_strDisplayName = strDisplayName;
    SERVICE_DESCRIPTION description;
    description.lpDescription = (LPSTR)(LPCTSTR)strDescription.c_str();
    if(::ChangeServiceConfig2(m_hService, SERVICE_CONFIG_DESCRIPTION, &description) == FALSE)
    {
        return false;
    }

    m_strDescription = strDescription;
    return true;
}

DWORD ServiceControl::GetStatus()
{
    if(m_hService == NULL)
    {
        return 0;
    }

    SERVICE_STATUS status;
    if(::QueryServiceStatus(m_hService, &status) == FALSE)
    {
        return 0;
    }

    return status.dwCurrentState;
}

 

//另附GlobalFunc.h

//#pragma once

#include <cctype>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;

void split(std::string& s, std::string& delim,std::vector<std::string >* ret)
{
    size_t last = 0;
    size_t index=s.find_first_of(delim,last);

    while (index!=std::string::npos)
    {
        ret->push_back(s.substr(last,index-last));
        last=index+1;
        index=s.find_first_of(delim,last);
    }

    if (index-last>0)
    {
        ret->push_back(s.substr(last,index-last));
    }
}

void string_replace(string & strBig, const string & strsrc, const string &strdst)
{       
    string::size_type pos=0;       
    string::size_type srclen=strsrc.size();       
    string::size_type dstlen=strdst.size();       
    while( (pos=strBig.find(strsrc, pos)) != string::npos)
    {               
        strBig.replace(pos, srclen, strdst);               
        pos += dstlen;       
    }
}

void string_trim(string& str)
{
   string::size_type pos1 = str.find_first_not_of(' ');
   string::size_type pos2 = str.find_last_not_of(' ');
   str = str.substr(pos1 == string::npos ? 0 : pos1,
      pos2 == string::npos ? str.length() - 1 : pos2 - pos1 + 1);
}

void string_tolower(string& src)
{
    transform(src.begin(),src.end(),src.begin(),tolower);
}

void string_toupper(string& src)
{
    transform(src.begin(),src.end(),src.begin(),toupper);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值