Output Console.WriteLine from WPF Windows Applications to actual console

After digging up a bit, I found this answer. The code is now:

namespace WpfConsoleTest
{
    public partial class App : Application
    {
        [DllImport("Kernel32.dll")]
        public static extern bool AttachConsole(int processId);

        protected override void OnStartup(StartupEventArgs e)
        {
            AttachConsole(-1);
            Console.WriteLine("Start");
            System.Threading.Thread.Sleep(1000);
            Console.WriteLine("Stop");
            Shutdown(0);
        }
    }
}

Calling the exe directly still has a nasty side effect, connected with the call returning immediately:

C:\test>WpfConsoleTest.exe

C:\test>Start
Stop

^^^^
The cursor will stay here waiting for the user to press enter!

The solution is, once again, to use start:

C:\test>start /wait WpfConsoleTest.exe
Start
Stop

Thanks for input!

Leave a Comment