Output Console.WriteLine from WPF Windows Applications to actual console

后端 未结 4 1212
青春惊慌失措
青春惊慌失措 2020-11-29 04:27

Background: I am struggling to add command line and batch processing capabilities to an existing WPF Windows Application. When I detect some options at startup I su

4条回答
  •  失恋的感觉
    2020-11-29 05:17

    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!

提交回复
热议问题