title: Output Console.WriteLine from WPF Windows Applications to actual console
body: <p>Background: I am struggling to add command line and batch processing capabilities to an existing WPF <em>Windows Application</em>. When I detect some options at startup I suppress the window from appearing, do some processing and quit immedietally. Now, because there's no UI I'd like to output some messages to stdout/stderr. Consider following code:</p>
  
  <pre><code>namespace WpfConsoleTest
  {
      public partial class App : Application
      {
          protected override void OnStartup(StartupEventArgs e)
          {
              Console.WriteLine("Start");
              System.Threading.Thread.Sleep(1000);
              Console.WriteLine("Stop");
              Shutdown(0);
          }
      }
  }
  </code></pre>
  
  <p>When I run from command line I would expect following output:</p>
  
  <pre><code>Start
  Stop
  </code></pre>
  
  <p>But instead:</p>
  
  <pre><code>C:\test&gt;WpfConsoleTest.exe
  
  C:\test&gt;
  </code></pre>
  
  <p>You <strong>can</strong> redirect output, though:</p>
  
  <pre><code>C:\test&gt;WpfConsoleTest.exe &gt; out.txt
  
  C:\test&gt;type out.txt
  Start
  Stop
  </code></pre>
  
  <p>Redirecting to CON does not work, unfortunately:</p>
  
  <pre><code>C:\test&gt;WpfConsoleTest.exe &gt; CON
  
  C:\test&gt;
  </code></pre>
  
  <p>Another problem is that WpfConsoleTest.exe quits <strong>immedietaly</strong> after start. So:</p>
  
  <pre><code>C:\test&gt;WpfConsoleTest.exe &gt; out.txt &amp; type out.txt
  
  C:\test&gt;
  </code></pre>
  
  <p>But:</p>
  
  <pre><code>C:\test&gt;WpfConsoleTest.exe &gt; out.txt &amp; ping localhost &gt; nul &amp; type out.txt
  Start
  Stop
  </code></pre>
  
  <p>The best solution I was able to come with so far is to use <code>start /B /wait</code>:</p>
  
  <pre><code>C:\test&gt;start /B /wait WpfConsoleTest.exe &gt; out.txt &amp; type out.txt
  Start
  Stop
  </code></pre>
  
  <p>This approach is mostly ok - if you wrap it up in a bat you can preserve error code and so on. The one huge downfall is that you get output after application ends, i.e. there's no way you can track progress, you have to wait for whatever is going on to finish.</p>
  
  <p>Therefore, my question is: <strong>How to output to parent console from WPF <em>Windows Application</em>?</strong> Also, why is so hard to grab stdout/stderr from WPF?</p>
  
  <p>I know that I could change application type to <em>Console Application</em> in project settings, but this has a nasty side effect - console window is visible all the time, even if you simply double click the exe. <a href="https://stackoverflow.com/a/718505/461632">This solution</a> also won't do, because it create <strong>a new</strong> console, even if application was run from cmd.</p>
  
  <p>EDIT: to clarify, I want my app to output to the <strong>existing</strong> console if there is one and <strong>not</strong> to create a new one if it is missing.</p>