Output Console.WriteLine from WPF Windows Applications to actual console

后端 未结 4 1224
青春惊慌失措
青春惊慌失措 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:03

    A WPF application will not have a console by default, but you can easily create one for it and then write to it just like in a console app. I've used this helper class before:

    public class ConsoleHelper
    {
        /// 
        /// Allocates a new console for current process.
        /// 
        [DllImport("kernel32.dll")]
        public static extern Boolean AllocConsole();
    
        /// 
        /// Frees the console.
        /// 
        [DllImport("kernel32.dll")]
        public static extern Boolean FreeConsole();
    }
    

    To use this in your example, you should be able to do this:

    namespace WpfConsoleTest
    {
        public partial class App : Application
        {
            protected override void OnStartup(StartupEventArgs e)
            {
                ConsoleHelper.AllocConsole(); 
                Console.WriteLine("Start");
                System.Threading.Thread.Sleep(1000);
                Console.WriteLine("Stop");
                ConsoleHelper.FreeConsole();
                Shutdown(0);
            }
        }
    }
    

    And now, if you run it from the command line, you should see "Start" and "Stop" written to the console.

提交回复
热议问题