Christian Ivicevic
Christian Ivicevic

Reputation: 10895

Combine console-based and windows-based application

Although I am using DirectX with a usual WinMain function in my application it happens that I want to create output to the console (with usual std::cout) if the application was started with specific parameters. Let's keep things simple: if the user calls the app with a --help parameter some help (using boost::program_options) should be displayed; otherwise, everything should work usually by creating a window etc.

How can I write output to a console (if the application was invoked through one) even in my windows application?


Background information: The general idea is that before running my game engine I would be able to run some tools (either external ones, or included into the engine) and get their output.


Current approach. I have right now two separate applications, one launcher and the engine, however I am looking to merge them if possible.

Upvotes: 0

Views: 308

Answers (1)

Karim ElDeeb
Karim ElDeeb

Reputation: 375

If all you need is to create a console window for your WinMain GUI application, then you need to call AllocConsole function. You are limited to one only per process.

Example in C ...

#include <stdio.h>

WinMain( ... ) {

    // parse the command line and check if --help is given

    AllocConsole(); // allocates console window for your process

    freopen("CON", "w", stdout); // redirects output to console

    printf( ... ); // test output to the console window

    FreeConsole(); // detaches your process from the console window

    // continue here

}

This will only create a console window on-demand, if you need to display something using a function like printf from within a GUI application. It does not make your application have both console and GUI subsystem. You need two .exe for that, so your current approach is the right one.

Upvotes: 2

Related Questions