代码中实现了删除服务,启动服务,停止服务,检测服务是否运行和服务是否存在等功能:
#pragma once #include <Windows.h> #include <tchar.h> //删除服务 /* 返回:1:表示成功 0:打开失败 -1:表示打开SCManager失败 */ int deleteService(LPCWSTR sSname) { SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT); SC_HANDLE hsev = NULL; if(scHandle != NULL) { hsev = OpenService(scHandle,sSname,SERVICE_ALL_ACCESS); SERVICE_STATUS mss; if(hsev != NULL) { QueryServiceStatus(hsev,&mss); if (mss.dwCurrentState != SERVICE_RUNNING) { ControlService(hsev,SERVICE_CONTROL_STOP,&mss); DeleteService(hsev); } CloseServiceHandle(hsev); } else { CloseServiceHandle(scHandle); return 0; } CloseServiceHandle(scHandle); } else return -1; return 1; } //启动KH客户端服务 void startService(LPCWSTR sSname) { SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT); SC_HANDLE hscv = NULL; if (scHandle != NULL) { hscv = OpenService(scHandle,sSname,SERVICE_START); if(hscv != NULL) { BOOL isSucess = StartService(hscv,0,NULL); DWORD err = 0; if (isSucess == 0) { err = GetLastError(); } CloseServiceHandle(hscv); } CloseServiceHandle(scHandle); } } //停止KH客户端服务 void stopService(LPCWSTR sSname) { SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT); SC_HANDLE hsev = NULL; if(scHandle != NULL) { hsev = OpenService(scHandle,sSname,SERVICE_ALL_ACCESS); SERVICE_STATUS mss; if(hsev != NULL) { QueryServiceStatus(hsev,&mss); if (mss.dwCurrentState == SERVICE_RUNNING) { ControlService(hsev,SERVICE_CONTROL_STOP,&mss); CloseServiceHandle(hsev); } } CloseServiceHandle(scHandle); } } BOOL isSvsRuning(LPCWSTR sSname) { BOOL ret = FALSE; SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT); SC_HANDLE hsev = NULL; if(scHandle != NULL) { hsev = OpenService(scHandle,sSname,SERVICE_ALL_ACCESS); SERVICE_STATUS mss; if(hsev != NULL) { QueryServiceStatus(hsev,&mss); if (mss.dwCurrentState == SERVICE_RUNNING) { ret = TRUE; CloseServiceHandle(hsev); } } CloseServiceHandle(scHandle); } return ret; } BOOL isSvsExist(LPCWSTR sSname) { BOOL ret = FALSE; SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT); SC_HANDLE hsev = NULL; if(scHandle != NULL) { hsev = OpenService(scHandle,sSname,SERVICE_ALL_ACCESS); DWORD err = GetLastError(); if (err == ERROR_SERVICE_DOES_NOT_EXIST) { ret = FALSE; } else { ret = TRUE; } if(hsev != NULL) { CloseServiceHandle(hsev); CloseServiceHandle(scHandle); } } return ret; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-07 00:33:04