用QT创建WINDOWS服务程序
Posted 朝闻道
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用QT创建WINDOWS服务程序相关的知识,希望对你有一定的参考价值。
我写一段,你将东西套进去就可以了,这里原来写的是定时服务,用的是boost::asio库,当然最好看一看boost::asio相关介绍。
#include <iostream>
#include <fstream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#ifdef _WIN32
#include <windows.h>
#endif
class printer
{
public:
printer(boost::asio::io_service &io)
{
........
}
~printer()
{
}
......
};
#ifdef _WIN32
boost::function0<void> console_ctrl_function;
SERVICE_STATUS_HANDLE g_ssh = NULL;
DWORD g_dwStatus = SERVICE_STOPPED;
int g_exitcode;
BOOL WINAPI console_ctrl_handler(DWORD ctrl_type)
{
switch (ctrl_type)
{
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_SHUTDOWN_EVENT:
console_ctrl_function();
return TRUE;
default:
return FALSE;
}
}
void SetStatus(DWORD dwStatus)
{
SERVICE_STATUS ss = {
SERVICE_WIN32_OWN_PROCESS,
SERVICE_STOPPED,
SERVICE_ACCEPT_STOP,
NO_ERROR,
0,
1,
5000};
ss.dwCurrentState = dwStatus;
SetServiceStatus(g_ssh, &ss);
g_dwStatus = dwStatus;
}
VOID WINAPI Handler(DWORD dwCtl)
{
switch (dwCtl)
{
case SERVICE_CONTROL_STOP:
console_ctrl_function();
break;
default:
SetStatus(g_dwStatus);
}
}
VOID WINAPI ServiceMain(DWORD dwArgc, LPTSTR *lpszArgv)
{
g_ssh = RegisterServiceCtrlHandler(lpszArgv[0], Handler);
SetStatus(SERVICE_START_PENDING);
try
{
boost::asio::io_service io;
printer p(io);
console_ctrl_function = boost::bind(&boost::asio::io_service::stop, &io);
SetStatus(SERVICE_RUNNING);
io.run();
g_exitcode = EXIT_SUCCESS;
}
catch (std::exception &e)
{
std::cerr << "[EXCEPTION]\t" << e.what() << std::endl;
g_exitcode = EXIT_FAILURE;
}
catch (const char *e)
{
std::cerr << "[EXCEPTION]\t" << e << std::endl;
g_exitcode = EXIT_FAILURE;
}
SetStatus(SERVICE_STOPPED);
}
int main(int argc, char **argv)
{
SERVICE_TABLE_ENTRY arSvc[] =
{
{L"ChinuxTeam TestServ v1.0", ServiceMain},
{NULL, NULL}
};
if (!StartServiceCtrlDispatcher(arSvc))
{
std::cerr << "Start Service Error" << std::endl;
return EXIT_FAILURE;
}
return g_exitcode;
}
#endif
qt solution有关于service的,跟qt整合得好一点,不过如果只是想实现服务,不是要搞什么跨平台啊,库啊之类的,在win上直接参考msdn吧,搜索也可以给出一大堆的代码
https://code.msdn.microsoft.com/CppWindowsService-cacf4948
不要谢 千万不要谢
以上是关于用QT创建WINDOWS服务程序的主要内容,如果未能解决你的问题,请参考以下文章