AttachConsole错误5:访问被拒绝

时间:2016-10-15 13:56:11

标签: c++ windows console-application

我正在使用Visual Studio 2013中的C ++控制台应用程序,在Windows上工作。

首先我使用FreeConsole分离了控制台,它有效;然后,将AllocConsole称为FreeConsole then AttachConsole not working建议,返回true表示成功;最后,我尝试使用AttachConsole将其附加回来,但没有发生任何事情 -

#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.

如何正确安装控制台?

1 个答案:

答案 0 :(得分:3)

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).