Windows Service Registry Sample

註冊Windows Service的指令
WinSrvReg.exe add 名稱 描述 路徑

WinSrvReg.exe add YourService WindowsService "C:\Program Files\YourService .exe"


反註冊Windows Service的指令
WinSrvReg.exe dele 名稱

WinSrvReg.exe dele YourService


WinSrvReg.cpp : Defines the entry point for the console application.
宣告

#include "stdafx.h"
#include <windows.h>
#include <winsvc.h>
#include <tchar.h>

bool createService(SC_HANDLE scm, LPCTSTR Servicename, LPCTSTR ServiceDescription, LPCTSTR program_path);
bool deleteService(SC_HANDLE scm, LPCTSTR Servicename);


tmain

int _tmain(int argc, _TCHAR* argv[]){
bool bRet;
TCHAR param[5][256];

SC_HANDLE scm;

   int i=0;
for (i=0; i<argc;i++){
     lstrcpy(param[i], argv[i]);
 _tprintf(_T("Param[%d] : %s\n"), i, param[i]);
}

scm = OpenSCManager (NULL, NULL,SC_MANAGER_ALL_ACCESS);

if(!scm){

_tprintf(_T("Open SCM failed !\n"));
return 0;
}

if(lstrcmp(_T("add"), param[1])==0){
bRet=createService(scm, param[2], param[3], param[4]);
}
else if (lstrcmp(_T("dele"), param[1])==0){

bRet= deleteService(scm, param[2]);
}
else if(lstrcmp(_T("start"), param[1])==0) {
}
else if(lstrcmp(_T("stop"), param[1])==0) {
}

CloseServiceHandle(scm);

return 1;
}


Create Service

bool createService(SC_HANDLE scm, LPCTSTR Servicename, LPCTSTR ServiceDescription, LPCTSTR program_path){

bool bRet;

SC_HANDLE scHandle=CreateService(scm,
Servicename,
ServiceDescription,
SERVICE_ALL_ACCESS,SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START,//SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
program_path,
0,0,0,0,0);

if(!scHandle){
_tprintf(_T("Create Windows service %s failed !\n"), Servicename);
bRet=FALSE;
}
else {
_tprintf(_T("Create Windows service %s successfully !\n"), Servicename);
CloseServiceHandle(scHandle);
bRet=TRUE;
}
return bRet;
}


Delete Service

bool (SC_HANDLE scm, LPCTSTR ServiceName){

SC_HANDLE scHandle=OpenService(scm,ServiceName,SERVICE_ALL_ACCESS);
if(scHandle==NULL){
_tprintf(_T("delete: Open  Windows service %s failed !\n"), ServiceName);
return FALSE;
}

if(DeleteService(scHandle)==0){
_tprintf(_T("delete : delete Windows service %s failed: %d !\n"), ServiceName, GetLastError());
CloseServiceHandle(scHandle);
return FALSE;
}

CloseServiceHandle(scHandle);
_tprintf(_T("delete Windows service %s successfully !\n"), ServiceName);

return TRUE;
}

Comments

Popular posts from this blog

[Linux] UVC Camera

UPnP Device Implementations

[UPnP] UPnP Implementers Corporation & UPnP Forum