简体   繁体   中英

FreeConsole then AttachConsole not working

I'm working with a C++ Console Application in Visual Studio 2013, working on Windows.

First I detached the console using FreeConsole, it works; then, I tried to attach it back using AttachConsole, but nothing happened --

#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

How could I find the lost Console back?

When you called FreeConsole(), your console ceases to exist. You cannot call AttachConsole() because there is nothing to attach to. You should instead use AllocConsole() to create a new console and then "attach" to it like so:

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

Then to free the console later on:

fclose(f);
FreeConsole();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM