How to do console output in WPF

If you wish to access standard input and output in your WPF app, you will have to compile it as a Console app and fire up the WPF application object manually.

Sample application: https://github.com/ikriv/WpfStdOut.

Attaching to the parent process console, as proposed by this CSharp411 article (thanks to Roel van Lisdonk for the pointer) insists on writing to the actual console and does not work well with redirected output.

Steps to apply to your application:

  1. Create WPF application as you would normally.
  2. You can use Console.Out.WriteLine(), but it would not go anywhere.
  3. Add Program.cs file with the following boilerplate code:
    public static void Main(string[] args)
    {
        var app = new App();
        app.InitializeComponent();
        app.Run();
    }
  4. Right click on the project, and choose Properties→Application.
  5. Change “Startup object” to YourNamespace.Program.
  6. Change “Output type” to “Console Application”>.

The downside is that when you run the WPF app from a shortcut, it will show a black console window in the background. This window can be hidden as described in this StackOverflow article.

This is not a major problem though, since the purpose of the console output is to either show it in the command line window, or to redirect it to a file or some stream. Push come to shove, one can create a start that launches the “console” application with a detached console (ProcessStartInfo.CreateNoWindow).

Leave a Reply

Your email address will not be published. Required fields are marked *