The code implements the functions of deleting the service, starting the service, stopping the service, detecting whether the service is running, and whether the service exists:
#pragma once#include <Windows.h> #include <tchar.h>//Delete Service/* Returns: 1: Indicates success 0: Open failed-1: Indicates open Scmanager failed */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);D eleteservice (Hsev);} Closeservicehandle (Hsev);} else {closeservicehandle (schandle); return 0;} Closeservicehandle (Schandle);} Elsereturn-1;return 1;} Start the KH client service 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 ISSUC ESS = StartService (hscv,0,null);D Word err = 0;if (issucess = = 0) {err = GetLastError ();} Closeservicehandle (HSCV);} Closeservicehandle (Schandle);}} Stop the KH Client serviceservice 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);D Word err = GetLastError (); if (err = = error_service_does_not_exist) {ret = FALSE;} Else{ret = TRUE;} if (Hsev! = NULL) {closeservicehandle (Hsev); Closeservicehandle (Schandle);}} return ret;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Windows service monitoring and operation related