Griffort
Griffort

Reputation: 1305

How to open Console during runtime [C++/Visual Studio]

Currently, I'm developing an SDL application with Visual Studio. Right now, if I want to have the console open in order to view output, I must enter the "properties of the project > Linker > System > SubSystem > Console" in order to enable it. When I'm ready to export however, I disable it.

However, I was wondering if there's anyway to open (or even close) the console window during runtime. Specifically, I wish to be able to press a key while the application is running in order open the console and view output.

I've tried using AllocConsole from windows.h, but while it does open a console window, it does not appear to display the output that normally appears whenever I manually set the application to use a Console window.

(Alternatively, I've been thinking I could open a second SDL window and display all output there, but I have no idea how to stream all output from the application to itself. Probably not the most convenient solution, but would work also.)

Upvotes: 2

Views: 730

Answers (1)

Gregory Pakosz
Gregory Pakosz

Reputation: 70234

You can use

if (::GetConsoleWindow() == NULL)
{
  if (::AllocConsole())
  {
    (void)freopen("CONIN$", "r", stdin);
    (void)freopen("CONOUT$", "w", stdout);
    (void)freopen("CONOUT$", "w", stderr);

    SetFocus(::GetConsoleWindow());
  }
}

Right before using printf

Upvotes: 4

Related Questions