如何将Qt窗口应用程序改成控制台程序呢?
下面进入正文,如何控制控制台程序退出呢?
这里采用线程方式,通过单独线程监视用户输入来执行是否退出程序。
监视线程头文件thread.h
#include <QThread>
#include "TDRServerDLL.h"
class CMyKeyEventThread : public QThread
{
Q_OBJECT
public:
explicit CMyKeyEventThread(QObject *parent = 0);
protected:
void run();
};
监视线程源文件thread.cpp
//按"Q"键退出应用程序
#include "thread.h"
#include <stdio.h>
CMyKeyEventThread::CMyKeyEventThread(QObject *parent) : QThread(parent)
{
}
void CMyKeyEventThread::run()
{
const char *pszTip = "Press 'Q' exit application.\n";
printf("%s\n", pszTip);
while (true)
{
printf("%s", pszTip);
if (getchar() == 'Q')
{
//这里为程序退出前需执行的操作
mwArray result;
TDRSvrStopScan(1, result);
printf("Done.");
TDRSvrUninit();
break;
}
}
printf("Done.");
}
main.cpp
#include "mainwindow.h"
#include "thread.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
//w.show();
CMyKeyEventThread *exitEvent = new CMyKeyEventThread();
QObject::connect(exitEvent, SIGNAL(finshed()), &a, SLOT(quit())); //连接信号
exitEvent->start();//启动线程
return a.exec();
}