title: AttachConsole Error 5: Access is denied
body: <p>I'm working with a C++ Console Application in Visual Studio 2013, working on Windows.</p>
  
  <p>First I detached the console using <code>FreeConsole</code>, it works; then, called <code>AllocConsole</code> as <a href="https://stackoverflow.com/questions/40059618/freeconsole-then-attachconsole-not-working">FreeConsole then AttachConsole not working</a> suggested, returns <code>true</code> meaning success; last, I tried to attach it back using <code>AttachConsole</code>, but nothing happened -- </p>
  
  <pre><code>#include &lt;psapi.h&gt;
  
  DWORD winpid = GetCurrentProcessId(); // get pid
  std::cout &lt;&lt; winpid; // it works    
  FreeConsole(); // console lost
  bool succeed = AllocConsole(); //succeeded.
  succeed = AttachConsole(winpid); // return false: failed.
  if (!succeed)
      LastError = GetLastError(); // Error Code 5
  </code></pre>
  
  <p><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx" rel="nofollow noreferrer">System Error Code 5 means</a>:</p>
  
  <pre><code>ERROR_ACCESS_DENIED
  5 (0x5)
  Access is denied.
  </code></pre>
  
  <p>How shall I attach the console properly?</p>