Windows系统服务创建步骤,常用类封装,废话不多说,直接上代码

 // ServceDemo.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include "WindwosService.h" unsigned __stdcall SvcRun (void *Params )
{
while()
{ for (int i = ;i < ;i++)
{
printf("%d\n",i);
} ::Sleep(**);
}
return ;
} int _tmain(int argc, _TCHAR* argv[])
{
#ifdef WIN32
InitService(argc,argv);
#endif // WIN32 #ifdef linux #endif // linux return ;
}

main函数文件代码

 #if !defined JX_About_Privilege
#define JX_About_Privilege #include <Windows.h>
// Windows提权类
class JXAboutPrivilege
{
public:
JXAboutPrivilege(void);
~JXAboutPrivilege(void);
// 提升关机权限
static BOOL EnableShutdownPrivileges( VOID );
// 提升结束进程的权限
static BOOL EnableTermProcessPrivileges( VOID );
// 提升加载驱动的权限
static BOOL EnableLoadDriverPrivileges( VOID ); static BOOL EnableDebugPrivilege(BOOL fEnable);
}; #endif

JXAboutPrivilege.h

 #include "StdAfx.h"
#include "JXAboutPrivilege.h" JXAboutPrivilege::JXAboutPrivilege(void)
{
} JXAboutPrivilege::~JXAboutPrivilege(void)
{
} BOOL JXAboutPrivilege::EnableShutdownPrivileges( VOID )
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
BOOL Result = FALSE; if ( !OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken) )
return FALSE; LookupPrivilegeValue( NULL, SE_SHUTDOWN_NAME, &(tkp.Privileges[].Luid) );
tkp.PrivilegeCount = ;
tkp.Privileges[].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges( hToken, FALSE, &tkp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES) NULL, );
DWORD dwError = GetLastError();
if ( ERROR_SUCCESS == dwError )
Result = TRUE; CloseHandle( hToken );
return Result;
} BOOL JXAboutPrivilege::EnableTermProcessPrivileges( VOID )
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
BOOL Result = FALSE; if ( !OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken) )
return FALSE; LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &(tkp.Privileges[].Luid) );
tkp.PrivilegeCount = ;
tkp.Privileges[].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges( hToken, FALSE, &tkp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES) NULL, );
DWORD dwError = GetLastError();
if ( ERROR_SUCCESS == dwError )
Result = TRUE; CloseHandle( hToken );
return Result;
} BOOL JXAboutPrivilege::EnableLoadDriverPrivileges( VOID )
{
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
BOOL Result = FALSE; if ( !OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken) )
return FALSE; LookupPrivilegeValue( NULL, SE_LOAD_DRIVER_NAME, &(tkp.Privileges[].Luid) );
tkp.PrivilegeCount = ;
tkp.Privileges[].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges( hToken, FALSE, &tkp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES) NULL, );
DWORD dwError = GetLastError();
if ( ERROR_SUCCESS == dwError )
Result = TRUE; CloseHandle( hToken );
return Result;
} BOOL JXAboutPrivilege::EnableDebugPrivilege(BOOL fEnable)
{
BOOL fOk = FALSE; // Assume function fails
HANDLE hToken;
// Try to open this process's access token
if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
{
// Attempt to modify the "Debug" privilege
TOKEN_PRIVILEGES tp;
tp.PrivilegeCount = ;
LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &tp.Privileges[].Luid);
tp.Privileges[].Attributes = fEnable ? SE_PRIVILEGE_ENABLED : ;
AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, NULL);
fOk = (GetLastError() == ERROR_SUCCESS);
CloseHandle(hToken);
}
return(fOk);
}

JXAboutPrivilege.cpp

 #if !defined JX_Service_Control
#define JX_Service_Control
#include <Windows.h> // Windows服务控制类
class JXServiceControl
{
public:
JXServiceControl(void);
~JXServiceControl(void);
public:
int ChangeServicePath( );
int createService();
int deleteService();
void startService();
void stopService();
BOOL isSvsRuning();
BOOL isSvsExist();
//设置服务名
void SetServiceName(const char * str);
//设置服务管理面板显示名字
void SetServiceShowName(const char *str);
//设置服务EXE文件位置
void SetExePath(const char *str);
private:
//服务名
char sSname[MAX_PATH+];
//服务Caption
char sShowName[MAX_PATH+];
//服务可执行文件路径
char sSvcExePath[MAX_PATH+];
}; #endif

JXServiceControl.h

WindwosService.h
 #include "WindwosService.h"

 SERVICE_STATUS ServiceStatus = {};
SERVICE_STATUS_HANDLE hStatus = NULL; void Run()
{
_beginthreadex(NULL, NULL, SvcRun, NULL, NULL, NULL);
} void WINAPI ControlHandler(DWORD fdwControl)
{
switch(fdwControl)
{
case SERVICE_CONTROL_STOP:
case SERVICE_CONTROL_SHUTDOWN:
ServiceStatus.dwWin32ExitCode = ;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
default: break;
}
SetServiceStatus(hStatus, &ServiceStatus);
} void WINAPI ServiceMain(DWORD dwArgc, LPTSTR* lpszArgv)
{ ZeroMemory(&ServiceStatus, sizeof(ServiceStatus));
ServiceStatus.dwServiceType = SERVICE_WIN32;
ServiceStatus.dwCurrentState = SERVICE_START_PENDING;// 正在启动中...
ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; hStatus = RegisterServiceCtrlHandler(SERVER_NAME, (LPHANDLER_FUNCTION)ControlHandler); // 注册当前服务的控制函数
if (!hStatus)
{
OutputDebugString(" RegisterServiceCtrlHandler 失败....\n");
return;
}
ServiceStatus.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus(hStatus, &ServiceStatus);// 修改服务状态
//////////////////////下方为启动主线程/////////////////////////////////////////
Run();
//////////////////////////////////////////////////////////////////////////
while()
{
::Sleep();
}
//::WaitForSingleObject(hThread,INFINITE); // 等待线程结束
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
ServiceStatus.dwWin32ExitCode = -;
SetServiceStatus(hStatus, &ServiceStatus);
} int InitService(int argc, TCHAR* argv[])
{
JXAboutPrivilege::EnableDebugPrivilege(TRUE);
JXAboutPrivilege::EnableLoadDriverPrivileges();
JXAboutPrivilege::EnableShutdownPrivileges();
JXAboutPrivilege::EnableTermProcessPrivileges(); if (argc == )
{
if (!stricmp(argv[],("-install")))
{
// InstallServices();
return ;
}
if (!stricmp(argv[], ("-uninstall")))
{
// UnInstallServices();
return ;
}
if (!stricmp(argv[], ("-run")))
{
Run();
while (TRUE)
Sleep();
return ;
}
}
SERVICE_TABLE_ENTRY DispatchTable[] = {
{ SERVER_NAME, (LPSERVICE_MAIN_FUNCTION)ServiceMain },
{ NULL, NULL }
}; StartServiceCtrlDispatcher(DispatchTable);
} void InstallServices()
{
TCHAR path_nor[MAX_PATH] = { };
GetModuleFileName(NULL, path_nor, MAX_PATH); JXServiceControl sc;
sc.SetExePath(path_nor);
sc.SetServiceName((SERVER_NAME));
sc.SetServiceShowName((SERVER_NAME)); if ( sc.isSvsExist() && sc.isSvsRuning() )
{
sc.stopService();
sc.ChangeServicePath();
}
else if ( sc.isSvsExist() )
{
sc.ChangeServicePath();
}
else if (!sc.isSvsExist())
{
sc.createService();
} sc.startService();
} void UnInstallServices()
{
TCHAR path_nor[MAX_PATH] = { };
GetModuleFileName(NULL, path_nor, MAX_PATH); JXServiceControl sc;
sc.SetExePath(path_nor);
sc.SetServiceName((SERVER_NAME));
sc.SetServiceShowName((SERVER_NAME)); if ( sc.isSvsExist() && sc.isSvsRuning() )
{
sc.stopService();
}
if( sc.isSvsExist() )
sc.deleteService();
}

WindwosService.cpp

 #include "StdAfx.h"
#include "JXServiceControl.h" JXServiceControl::JXServiceControl(void)
{
memset(sSname,,MAX_PATH);
memset(sShowName,,MAX_PATH);
memset(sSvcExePath,,MAX_PATH);
} JXServiceControl::~JXServiceControl(void)
{ } int JXServiceControl::ChangeServicePath()
{
SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CONNECT);
SC_HANDLE hsev = NULL;
if(scHandle != NULL)
{
hsev = OpenService(scHandle,sSname,SERVICE_ALL_ACCESS);
if(hsev != NULL)
{
BOOL bRet = ChangeServiceConfig(
hsev,
SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS,
SERVICE_AUTO_START,
SERVICE_ERROR_IGNORE,
sSvcExePath,
NULL,
NULL,
NULL,
NULL,
NULL,
sShowName
);
CloseServiceHandle(hsev); }
else
{
CloseServiceHandle(scHandle);
return ;
}
CloseServiceHandle(scHandle);
}
else
return -; return ;
} int JXServiceControl::createService()
{
SC_HANDLE scHandle = OpenSCManager(NULL,NULL,SC_MANAGER_CREATE_SERVICE);
if (scHandle == NULL)
{
return -;
}
SC_HANDLE hsvc = CreateService(scHandle,sSname,sShowName,SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS,SERVICE_AUTO_START,
SERVICE_ERROR_IGNORE,sSvcExePath,
NULL,NULL,NULL,NULL,NULL);
if (hsvc != NULL)
{
CloseServiceHandle(hsvc);
}
else
{
return ;
}
CloseServiceHandle(scHandle);
return ;
} int JXServiceControl::deleteService()
{
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 ;
}
CloseServiceHandle(scHandle);
}
else return -;
return ;
} void JXServiceControl::startService()
{
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,,NULL);
DWORD err = ;
if (isSucess == )
{
err = GetLastError();
}
CloseServiceHandle(hscv);
}
CloseServiceHandle(scHandle);
}
} void JXServiceControl::stopService()
{
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 JXServiceControl::isSvsRuning()
{
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 JXServiceControl::isSvsExist()
{
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;
} void JXServiceControl::SetServiceName(const char * str)
{
strcpy_s(sSname,MAX_PATH,str);
} void JXServiceControl::SetServiceShowName(const char *str)
{
strcpy_s(sShowName,MAX_PATH,str);
} void JXServiceControl::SetExePath(const char *str)
{
strcpy_s(sSvcExePath,MAX_PATH,str);
}

JXServiceControl.cpp

转载请注明出处....

代码栗子:http://pan.baidu.com/s/1WHQ5w

VC Windows系统服务创建代码的更多相关文章

  1. windows系统服务编程代码示例分享

    #include"XXXX.h" //包含的头文件 //定义全局函数变量 void Init(); BOOL IsInstalled(); BOOL Install(); BOOL ...

  2. 深入解析Windows窗体创建和消息分发

    Windows GUI採用基于事件驱动的编程模型,其实差点儿全部的界面库都是这样做的.在纯粹的Window32 SDK编程时代.人们还能够搞懂整个Windows窗口创建和消息的流通过程.可是在如今各种 ...

  3. 深入解析Windows窗口创建和消息分发(三个核心问题:怎么将不同的窗口过程勾到一起,将不同的hwnd消息分发给对应的CWnd类去处理,CWnd如何简单有效的去处理消息,由浅入深,非常清楚) good

    笔记:争取不用看下面的内容,只看自己的笔记,就能记住这个流程,就算明白了: _tWinMain-->AfxWinMain,它调用四个函数: -->AfxWinInit用于做一些框架的初始化 ...

  4. C#-Windows服务创建和运行

    Windows服务创建和运行    适用场景: ASP.Net通常是一个无状态的提供程序,不支持持续运行代码或者定时执行某段代码,所以我们需要构建自己的Windows服务来运行那些定时任务. 项目中需 ...

  5. VC Windows API获得桌面所有窗口句柄的方法

    VC Windows API应用之GetDesktopWindow ——获得桌面所有窗口句柄的方法 Windows API Windows 这个多作业系统除了协调应用程序的执行.分配内存.管理资源…之 ...

  6. MongoDB安装,启动,注册为windows系统服务

    MongoDB安装与启动 周建旭 2014-08-10 解压完后配置环境变量 下载Windows 32-bit或64-bit版本并解压缩,程序文件都在bin目录中,其它两个目录分别是C++调用是的头文 ...

  7. C#开发奇技淫巧一:调试windows系统服务

    原文:C#开发奇技淫巧一:调试windows系统服务 windows系统服务不能直接运行,只能在安装完服务之后启动.暂停.继续.停止服务,导致服务的调试不能使用一般的断点调试. 要调试系统服务,可以采 ...

  8. 安装windows服务批处理代码

    批处理是DOS时代比较常用的方法之一,目前来说也是一种高效的方法,复制代码到文本文件中,保存并修改文件扩展名为“*.bat”. 安装windows服务批处理代码如下: @echo off set fi ...

  9. Windows中创建桌面快捷方式

    Windows中创建桌面快捷方式 -------------- -------------- -------------- --------------

随机推荐

  1. Java多线程中易混淆的概念

    概述 最近在看<ThinKing In Java>,看到多线程章节时觉得有一些概念比较容易混淆有必要总结一下,虽然都不是新的东西,不过还是蛮重要,很基本的,在开发或阅读源码中经常会遇到,在 ...

  2. js-ajax实现获取xmlHttp对象

    //获取xmlHttp对象 function createXMLHttp() { var xmlhttp; //对于大多数浏览器适用 if (window.XMLHttpRequest) { xmlh ...

  3. codevs 1198 国王游戏

    传送门 题目描述 Description 恰逢 H 国国庆,国王邀请 n 位大臣来玩一个有奖游戏.首先,他让每个大臣在左.右手上面分别写下一个整数,国王自己也在左.右手上各写一个整数.然后,让这 n位 ...

  4. xcode 发展史 及 做iOS 必须知道的小知识

    Xcode 3.0 是开发人员建立 Mac OS X 应用程序的最快捷方式,也是利用新的苹果电脑公司技术的最简单的途径.Xcode 3.0 将Mac OS X的轻松使用,UNIX 能量以及高性能的开发 ...

  5. STM8S学习笔记-时钟控制2

    今天把时钟系统的最后部分,时钟安全系统(CSS)和时钟输出功能(CCO),做一个简答的说明. 1.时钟安全系统(以下简称CSS) CSS功能很简单,就是监控HSE是否实效(如果系统使用HSE作为主时钟 ...

  6. 彻底卸载 RAD Studio 2009/2010/XE+ 的步骤

    重新安装 RAD 系列时,建议将上一个版本彻底卸载,彻底卸载 RAD Studio 2009/2010/XE+ 的步骤: 控制面板-->添加/删除程序中执行了卸载操作以后, 还需要做以下工作: ...

  7. SignTool.exe(签名工具)

    水漂收集 -- SignTool.exe(签名工具) =============C#.Net 篇目录============== 签名工具是一个命令行工具,用于用证书对文件进行数字签名,验证文件和时间 ...

  8. 7.5.1 Point-in-Time Recovery Using Event Times 使用Event Times 基于时间点恢复

    7.5.1 Point-in-Time Recovery Using Event Times 使用Event Times 基于时间点恢复 表明开始和结束时间用于恢复, 指定 --start-datet ...

  9. 【最短路】Vijos P1046 观光旅游

    题目链接: https://vijos.org/p/1046 题目大意: 给n个点(n<=100),m条无向边(m<=10000),问这张图的最小环长度. (注意:无自环,同一个点对之间的 ...

  10. 【Python排序搜索基本算法】之Dijkstra算法

    Dijkstra算法和前一篇的Prim算法非常像,区别就在于Dijkstra算法向最短路径树(SPT)中添加顶点的时候,是按照ta与源点的距离顺序进行的.OSPF动态路由协议就是用的Dijkstra算 ...