The core code is as follows:
// MSVC2019 toolchain /* * The library is needed by function SendMessageA() * This code is sometimes necessary, sometimes not */ #pragma comment(lib, "User32.lib") #include "widget.h" #include <QApplication> #include <Windows.h> #include <QDebug> int main(int argc, char *argv[]) { QApplication a(argc, argv); AllocConsole(); SetConsoleTitleA("ConsoleAllocFreeTest"); HWND handle = GetConsoleWindow(); FILE *pf; //Bind the standard output device to the console freopen_s(&pf, "CONOUT$", "w", stdout); //Bind the standard error output device to the console freopen_s(&pf, "CONOUT$", "w", stderr); printf_s("This is console test...\n"); /* * qDebug() outputs informations to standard error output device by default * So we need to bind the console to the standard error output device. */ qDebug() << "qDebug() outputs information to standard output device by default."; qDebug() << "qDebug() 默认将信息输出到标准输出。"; /* * use function 'SendMessageA' to close console window. * FreeConsole() only can unbind the program and console. * In addition, after this funtion is called, * closing the console will not cause the program to close together */ FreeConsole(); // close the console SendMessageA(handle, WM_CLOSE, 0, 0); Widget w; w.show(); return a.exec(); }