| 28 | static bool withConsole = false; |
| 29 | |
| 30 | SystemConsole::SystemConsole() |
| 31 | { |
| 32 | // If some output handle (stdout/stderr) is not attached to a |
| 33 | // console, we can attach the process to the parent process console. |
| 34 | bool unknownOut = (::GetFileType(::GetStdHandle(STD_OUTPUT_HANDLE)) == FILE_TYPE_UNKNOWN); |
| 35 | bool unknownErr = (::GetFileType(::GetStdHandle(STD_ERROR_HANDLE)) == FILE_TYPE_UNKNOWN); |
| 36 | if (unknownOut || unknownErr) { |
| 37 | // AttachConsole() can fails if the parent console doesn't have a |
| 38 | // console, which is the most common, i.e. when the user |
| 39 | // double-click a shortcut to start the program. |
| 40 | if (::AttachConsole(ATTACH_PARENT_PROCESS)) { |
| 41 | // In this case we're attached to the parent process |
| 42 | // (e.g. cmd.exe) console. |
| 43 | withConsole = true; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | if (withConsole) { |
| 48 | // Here we redirect stdout/stderr to use the parent console's ones. |
| 49 | if (unknownOut) |
| 50 | std::freopen("CONOUT$", "w", stdout); |
| 51 | if (unknownErr) |
| 52 | std::freopen("CONOUT$", "w", stderr); |
| 53 | |
| 54 | // Synchronize C++'s cout/cerr streams with C's stdout/stderr. |
| 55 | std::ios::sync_with_stdio(); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | SystemConsole::~SystemConsole() |
| 60 | { |
nothing calls this directly
no outgoing calls
no test coverage detected