Redirect console.writeline from windows application to a string

前端 未结 4 1805
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 08:29

I have an external dll written in C# and I studied from the assemblies documentation that it writes its debug messages to the Console using Console.WriteLine.

4条回答
  •  情书的邮戳
    2020-11-28 08:52

    As it seems like you want to catch the Console output in realtime, I figured out that you might create your own TextWriter implementation that fires an event whenever a Write or WriteLine happens on the Console.

    The writer looks like this:

        public class ConsoleWriterEventArgs : EventArgs
        {
            public string Value { get; private set; }
            public ConsoleWriterEventArgs(string value)
            {
                Value = value;
            }
        }
    
        public class ConsoleWriter : TextWriter
        {
            public override Encoding Encoding { get { return Encoding.UTF8; } }
    
            public override void Write(string value)
            {
                if (WriteEvent != null) WriteEvent(this, new ConsoleWriterEventArgs(value));
                base.Write(value);
            }
    
            public override void WriteLine(string value)
            {
                if (WriteLineEvent != null) WriteLineEvent(this, new ConsoleWriterEventArgs(value));
                base.WriteLine(value);
            }
    
            public event EventHandler WriteEvent;
            public event EventHandler WriteLineEvent;
        }
    

    If it's a WinForm app, you can setup the writer and consume its events in the Program.cs like this:

        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        static void Main()
        {
            using (var consoleWriter = new ConsoleWriter())
            {
                consoleWriter.WriteEvent += consoleWriter_WriteEvent;
                consoleWriter.WriteLineEvent += consoleWriter_WriteLineEvent;
    
                Console.SetOut(consoleWriter);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }
    
        static void consoleWriter_WriteLineEvent(object sender, Program.ConsoleWriterEventArgs e)
        {
            MessageBox.Show(e.Value, "WriteLine");
        }
    
        static void consoleWriter_WriteEvent(object sender, Program.ConsoleWriterEventArgs e)
        {
            MessageBox.Show(e.Value, "Write");
        }
    

提交回复
热议问题