QCoreApplication::exec()无法正常返回的问题

QCoreApplication::exec()无法正常返回的问题

在Qt开发的控制台程序中,使用QCoreApplication::exec()来开启主线程的事件循环,当关闭控制台程序的时候,有时会碰到exec()函数无法正常返回的情况,造成exec()无法正常返回的原因如下(参考Qt的帮助文档)

[static] int QCoreApplication::exec()

Enters the main event loop and waits until exit() is called. Returns the value that was passed to exit() (which is 0 if exit() is called via quit()).

It is necessary to call this function to start event handling. The main event loop receives events from the window system and dispatches these to the application widgets.

To make your application perform idle processing (by executing a special function whenever there are no pending events), use a QTimer with 0 timeout. More advanced idle processing schemes can be achieved using processEvents().

We recommend that you connect clean-up code to the aboutToQuit() signal, instead of putting it in your application’s main() function because on some platforms the exec() call may not return. For example, on Windows when the user logs off, the system terminates the process after Qt closes all top-level windows. Hence, there is no guarantee that the application will have time to exit its event loop and execute code at the end of the main() function after the exec() call.

所以解决这类问题的方式是

#include <QtCore/QCoreApplication>
#include <windows.h>
//#include <stdio.h>

BOOL HandlerRoutine(DWORD dwCtrlType)
{
	switch (dwCtrlType)
	{
	case CTRL_C_EVENT:
		printf("ctrl+c\n");
		return TRUE;
	case CTRL_CLOSE_EVENT:
		printf("ctrl close\n");
		return TRUE;
	case CTRL_BREAK_EVENT:
		printf("CTRL_BREAK_EVENT\n");
	case CTRL_LOGOFF_EVENT:
		printf("CTRL_LOGOFF_EVENT\n");
	case CTRL_SHUTDOWN_EVENT:
		printf("CTRL_SHUTDOWN_EVENT\n");
	default:
		return FALSE;
	}
}

int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);
    
	SetConsoleCtrlHandler((PHANDLER_ROUTINE)HandlerRoutine, TRUE);
 	return a.exec();
}

当程序结束后,会先执行HandlerRoutine()函数,可以将一些对象的销毁和内存的释放放在这个函数中。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值