概述
如何使用QT来开启一个服务呢?
新建一个QT工程,添加如下代码:
#include <windows.h>
#include <string>
/*******************************************
* 函数:StartServiceExistByName
* 参数:strDestServiceName
* 功能:判断服务状态并启动
* 返回值:
* TRUE 服务启动成功
* FALSE 服务启动失败
********************************************/
bool StartServiceByName(std::string strDestServiceName)
{
bool bServiceStatus = FALSE;
SC_HANDLE schSCManager = NULL ;
SC_HANDLE schService = NULL ;
SERVICE_STATUS_PROCESS ssStatus;
DWORD dwBytesNeeded = 0 ;
char szSvcName[MAX_PATH] = {0};
memcpy_s(szSvcName,MAX_PATH,strDestServiceName.c_str(),strDestServiceName.length());
// Get a handle to the SCM database.
schSCManager = OpenSCManager(
NULL , // local computer
NULL , // ServicesActive database
SC_MANAGER_ALL_ACCESS); // full access rights
if ( NULL == schSCManager)
{
//LOG(level_error, "OpenSCManager failed (%d)" , GetLastError());
return bServiceStatus;
}
// Get a handle to the service.
schService = OpenServiceA(
schSCManager, // SCM database
szSvcName, // name of service
SERVICE_ALL_ACCESS/* | DELETE*/); // full access
if (schService == NULL )
{
//LOG(level_error, "OpenService failed (%d)" , GetLastError());
CloseServiceHandle(schSCManager);
return bServiceStatus;
}
if (!QueryServiceStatusEx(
schService, // handle to service
SC_STATUS_PROCESS_INFO, // information level
(LPBYTE) &ssStatus, // address of structure
sizeof (SERVICE_STATUS_PROCESS), // size of structure
&dwBytesNeeded ) ) // size needed if buffer is too small
{
//LOG(level_error, "QueryServiceStatusEx failed (%d)" , GetLastError());
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return bServiceStatus;
}
else
{
switch (ssStatus.dwCurrentState)
{
case SERVICE_STOPPED:
case SERVICE_STOP_PENDING:
//LOG(level_info, "%s Service status is Stop ", szSvcName);
break ;
case SERVICE_PAUSED:
case SERVICE_PAUSE_PENDING:
//LOG(level_info, "%s Service status is Pause ", szSvcName);
break ;
case SERVICE_CONTINUE_PENDING:
case SERVICE_RUNNING:
case SERVICE_START_PENDING:
//LOG(level_info, "%s Service status is Running ", szSvcName);
bServiceStatus = TRUE;
break ;
}
}
if (bServiceStatus == FALSE)
{
StartService(schService,0,NULL);
Sleep(500);
//LOG(level_error, "StartService failed (%d)" , GetLastError());
// 获得服务的当前状态
QueryServiceStatusEx(schService,SC_STATUS_PROCESS_INFO,(LPBYTE) &ssStatus,sizeof (SERVICE_STATUS_PROCESS),&dwBytesNeeded );
if (SERVICE_RUNNING == ssStatus.dwCurrentState)
{
bServiceStatus = TRUE;
}
}
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
return bServiceStatus;
}
调用起来很简单:
StartServiceByName("XXX");
其中 XXX 是服务名,应该取下图任务管理器中红框那一列的名字
最后
以上就是羞涩宝马为你收集整理的QT开启服务的全部内容,希望文章能够帮你解决QT开启服务所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复