This might be coming a bit late, but I can confirm that SetConsoleCtrlHandler() definitely is the way to go. I have used it several times. I once wrote an OS-independent abstraction of a "termination handler" that would emit a Qt signal when receiving a termination request from the OS. The implementation for Windows console applications used SetConsoleCtrlHandler() and the design was roughly along these lines (but with some hiding of the internal structures):
Q_OBJECT
signals:
void terminated();
public:
void emitTerminated() {
emit terminated();
}
};
Handler *handler = NULL;
BOOL WINAPI winHandler(DWORD /*dwCtrlType*/) {
if (handler == NULL)
return FALSE;
handler->emitTerminated();
return TRUE;
}
void registerHandler() {
assert(handler == NULL);
handler = new Handler;
SetConsoleCtrlHandler(winHandler, TRUE);
}
void unregisterHandler() {
handler->deleteLater();
handler = NULL;
SetConsoleCtrlHandler(winHandler, FALSE);
}
class Handler : public QObject {
Q_OBJECT
signals:
void terminated();
public:
void emitTerminated() {
emit terminated();
}
};
QMutex mutex;
Handler *handler = NULL;
BOOL WINAPI winHandler(DWORD /*dwCtrlType*/) {
QMutexLocker lock(&mutex);
if (handler == NULL)
return FALSE;
handler->emitTerminated();
return TRUE;
}
void registerHandler() {
QMutexLocker lock(&mutex);
assert(handler == NULL);
handler = new Handler;
SetConsoleCtrlHandler(winHandler, TRUE);
}
void unregisterHandler() {
QMutexLocker lock(&mutex);
handler->deleteLater();
handler = NULL;
SetConsoleCtrlHandler(winHandler, FALSE);
}
To copy to clipboard, switch view to plain text mode
You can then connect to the Handler::terminated() signal to be notified of the termination request.
Bookmarks