[SOLVED] Attach console to GUI application on Windows
-
I was looking at this article:
https://justcheckingonall.wordpress.com/2008/08/29/console-window-win32-app/
which explains how to attach a console to a Win32/GUI application.I was wondering if there was a more Qt-like way of doing this? I would love a console in debug mode. Also, if the console was interactive (like, I could type commands while the GUI is still running) it would be awesome; but I doubt this is possible...
EDIT
As an alternative solution, would it be possible to use some GUI widgets from Qt to actually run console commands just like I would do from the Windows console (cmd.exe) ? -
If you want console just to display output in debug configuration you can simply specify that application is in the console application.
http://doc.qt.io/qt-4.8/qmake-common-projects.html -
previous reply text removed as it's useless, read next
Re-EDIT
The solution was far simpler than I thought... AllocConsole() creates a new console; AttachConsole() will link the new console to the application; then it's just a matter of redirecting I/O to the new console by reopening the std streams...#include <QApplication> #include <QWidget> #define DEBUG #ifdef DEBUG #include <windows.h> #include <stdio.h> #endif int main(int argc, char *argv[]){ #ifdef DEBUG // detach from the current console window // if launched from a console window, that will still run waiting for the new console (below) to close // it is useful to detach from Qt Creator's <Application output> panel FreeConsole(); // create a separate new console window AllocConsole(); // attach the new console to this application's process AttachConsole(GetCurrentProcessId()); // reopen the std I/O streams to redirect I/O to the new console freopen("CON", "w", stdout); freopen("CON", "w", stderr); freopen("CON", "r", stdin); #endif puts("creating QApplication"); QApplication app(argc, argv); puts("creating QWidget"); QWidget w; puts("showing widget"); w.show(); puts("type something:"); getchar(); w.resize(320, 240); puts("yeeeey! It works!"); app.exec(); return 0; }
Wherever the application is launched from now it will open it's own console window and use that for I/O. Please note that this is the naive way, I didn't make checks for possible failures, so you should add them for a fail-safe application.
So that's it, sorry for opening a thread and eventually answering the quesiton myself. I hope it'll be useful to others as well ;) -
@T3STY said:
freopen("CON", "w", stdout);
freopen("CON", "w", stderr);
freopen("CON", "r", stdin);Thanks for this! I'd been trying to do this the 'Windows way' and never actually seeing the output - but replacing my _open_osfhandle approach with the simple one above fixed it for me. Lifesaver! Cheers.
-
@JimboStlawrence
Are you aware that if you run your Qt GUI app from Qt Creator debugger you automatically get a console window there anyway?