调用QCoreApplication::hasPendingEvents()
或QAbstractEventDispatcher::instance()->hasPendingEvents()
在线程内部工作正常.但是,在它之外,后者(具有适当的参数)总是返回false
(前者不能在外部使用,因为它指的是从中调用它的线程).
这是一个完整的代码:
#include <QCoreApplication>
#include <QAbstractEventDispatcher>
#include <QThread>
#include <QDebug>
bool hasPendingEvents(QThread *thread = 0) {
return QAbstractEventDispatcher::instance(thread)->hasPendingEvents();
}
class MyObject: public QObject {
Q_OBJECT
public slots:
void Run() {
qDebug() << __LINE__ << hasPendingEvents() << QCoreApplication::hasPendingEvents();
QThread::sleep(1);
}
};
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
QThread thread;
MyObject t;
t.moveToThread(&thread);
thread.start();
for (int i = 0; i<4; ++i) QMetaObject::invokeMethod(&t, "Run", Qt::QueuedConnection);
for (int i = 0; i<10; ++i) {
QThread::msleep(500); …
Run Code Online (Sandbox Code Playgroud) 我有一个设备将数据发送到COM端口.我想在没有插入时模拟这个设备.我认为这可以通过简单地将数据发送到特定的COM端口来实现:
int main() {
char *port = "\\\\.\\COM40";
HANDLE hCom = CreateFile(port, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hCom==INVALID_HANDLE_VALUE) return 0;
DWORD writeBytes;
int buffer = 0xDEADBEAF;
BOOL success = WriteFile(hCom, &buffer, 4, &writeBytes, NULL);
FlushFileBuffers(hCom);
Sleep(1000);
HANDLE hCom2 = CreateFile(port, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (hCom2==INVALID_HANDLE_VALUE) return 0; // Exit. GetLastError() == 5
DWORD readBytes;
success = ReadFile(hCom2, &buffer, 4, &readBytes, NULL);
CloseHandle(hCom);
CloseHandle(hCom2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,这不起作用,第二个 …