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:
    [STAThread]
    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).

6 Comments


  1. I get this error when trying to do this
    ‘The calling thread must be STA, because many UI components require this.’

    Reply

    1. I read that sample code, you are missing this in the Program.cs thing above
      [STAThread]

      Reply

      1. Tristan, thanks for the comment! Yes, this error happens when the Main method is missing [STAThread] attribute. Kudos for finding it out yourself.

        [STAThread] is present in the sample project, but not in the example I included in the post. After two years, I am not sure what was the reason: either way, I have added it now.

        Reply

  2. Ivan, Thank you. Extremely smart and useful.

    If I have an unmanaged DLL fired from my WPF app, would it have access to the console window for both input and output? I should probbaly try it!

    Cheers

    I. Konuk

    Reply

Leave a Reply to ikriv Cancel reply

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