From 9f971deb06bd6c2aef20d19199f11ef51a2fc14d Mon Sep 17 00:00:00 2001 From: Zhao Yuhang <2546789017@qq.com> Date: Sun, 22 Oct 2023 16:05:25 +0800 Subject: [PATCH] Win: minor improvement of the console debug trick If the application has already attached to the console, the AttachConsole() API will fail but we can still redirect our output to the console. The previous code doesn't take this case into consideration, now it's covered by this patch. Please refer to the "Remarks" section: https://learn.microsoft.com/en-us/windows/console/attachconsole Change-Id: I1c5033cc962dcd5a757ff15cc677a51e21330e0b Reviewed-by: Thiago Macieira (cherry picked from commit fd300f143fd30947bba60a03d614acd2711b635f) Reviewed-by: Qt Cherry-pick Bot --- src/corelib/kernel/qcoreapplication.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/corelib/kernel/qcoreapplication.cpp b/src/corelib/kernel/qcoreapplication.cpp index 5ee430222fe..a80efbb5622 100644 --- a/src/corelib/kernel/qcoreapplication.cpp +++ b/src/corelib/kernel/qcoreapplication.cpp @@ -577,7 +577,9 @@ void QCoreApplicationPrivate::initConsole() return; consoleAllocated = true; } else if (env.compare(u"attach"_s, Qt::CaseInsensitive) == 0) { - if (AttachConsole(ATTACH_PARENT_PROCESS) == FALSE) + // If the calling process is already attached to a console, + // the error code returned is ERROR_ACCESS_DENIED. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::GetLastError() != ERROR_ACCESS_DENIED) return; } else { // Unknown input, don't make any decision for the user.