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:
- Create WPF application as you would normally.
- You can use
Console.Out.WriteLine()
, but it would not go anywhere. - Add
Program.cs
file with the following boilerplate code:[STAThread] public static void Main(string[] args) { var app = new App(); app.InitializeComponent(); app.Run(); }
- Right click on the project, and choose Properties→Application.
- Change “Startup object” to
YourNamespace.Program
. - 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).
Permalink
I get this error when trying to do this
‘The calling thread must be STA, because many UI components require this.’
Permalink
I read that sample code, you are missing this in the Program.cs thing above
[STAThread]
Permalink
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.
Permalink
Thank-you for this, Ivan – you probably saved me a number of hours of scratching my head!
Permalink
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
Permalink