AttachConsole Error 5: Access is denied

2019-02-20 14:21发布

问题:

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, called AllocConsole as FreeConsole then AttachConsole not working suggested, returns true meaning success; last, 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
bool succeed = AllocConsole(); //succeeded.
succeed = AttachConsole(winpid); // return false: failed.
if (!succeed)
    LastError = GetLastError(); // Error Code 5

System Error Code 5 means:

ERROR_ACCESS_DENIED
5 (0x5)
Access is denied.

How shall I attach the console properly?

回答1:

Remove the AllocConsole call before AttachConsole.

From the documentation: A process can be attached to at most one console. If the calling process is already attached to a console, the error code returned is ERROR_ACCESS_DENIED (5).