FreeConsole 然后 AttachConsole 不工作

FreeConsole then AttachConsole not working

我在 Visual Studio 2013 年使用 C++ 控制台应用程序,致力于 Windows。

首先,我使用 FreeConsole 分离了控制台,它可以工作;然后,我尝试使用 AttachConsole 将其附加回去,但没有任何反应 --

#include <psapi.h>

DWORD winpid = GetCurrentProcessId(); // get pid
std::cout << winpid; // it works    
FreeConsole(); // console lost
std::cout << "Lost to the bit bucket"; //nothing happen, as expected
AttachConsole(winpid); // try find the console back....
std::cout << "c"; // ... but failed

如何找回丢失的控制台?

当您调用 FreeConsole() 时,您的控制台将不复存在。您不能调用 AttachConsole(),因为没有可附加的内容。您应该改为使用 AllocConsole() 创建一个新控制台,然后 "attach" 像这样:

AllocConsole();
FILE* f;
freopen_s(&f, "CONOUT$", "w", stdout);

然后稍后释放控制台:

fclose(f);
FreeConsole();