Redirect Console.Write… Methods to Visual Studio's Output Window While Debugging

前端 未结 7 1373
死守一世寂寞
死守一世寂寞 2020-12-03 04:47

From a Console Application project in Visual Studio, I want to redirect Console\'s output to the Output Window

相关标签:
7条回答
  • 2020-12-03 04:58

    Change application type to Windows before debugging. Without Console window, Console.WriteLine works like Trace.WriteLine. Don't forget to reset application back to Console type after debugging.

    0 讨论(0)
  • 2020-12-03 05:05
        class DebugWriter : TextWriter
        {        
            public override void WriteLine(string value)
            {
                Debug.WriteLine(value);
                base.WriteLine(value);
            }
    
            public override void Write(string value)
            {
                Debug.Write(value);
                base.Write(value);
            }
    
            public override Encoding Encoding
            {
                get { return Encoding.Unicode; }
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
    #if DEBUG         
                if (Debugger.IsAttached)
                    Console.SetOut(new DebugWriter());   
    #endif
    
                Console.WriteLine("hi");
            }
        }
    

    ** note that this is roughed together almost pseudo code. it works but needs work :) **

    0 讨论(0)
  • 2020-12-03 05:09

    Try Trace.Write and use DebugView

    0 讨论(0)
  • 2020-12-03 05:10

    Actually, there is an easiest way: In the "Options" window of Visual Studio (from the Tools menu), go to "Debugging" then check the option "Redirect All Output Window Text to the Immediate Window".

    0 讨论(0)
  • 2020-12-03 05:16

    Thanks, Alex F, nice solution, but didn't work for me, because my project was created by cmake. So, to do as Alex F suggested, add WIN32 or MACOSX_BUNDLE to add_executable

    add_executable(target_name WIN32 <source list>)
    

    Or, if you can't edit the CMakeList.txt, you can add -DCMAKE_WIN32_EXECUTABLE=1 to the cmake configure command.

    0 讨论(0)
  • 2020-12-03 05:22

    Note if you're using dkackman's method but you want to write the output to BOTH the console window and the debug window, then you can slightly modify his code like this:

    class DebugWriter : TextWriter
    {
        //save static reference to stdOut
        static TextWriter stdOut = Console.Out;
    
        public override void WriteLine(string value)
        {
            Debug.WriteLine(value);
            stdOut.WriteLine(value);
            base.WriteLine(value);
        }
    
        public override void Write(string value)
        {
            Debug.Write(value);
            stdOut.Write(value);
            base.Write(value);
        }
    
        public override Encoding Encoding
        {
            get { return Encoding.Unicode; }
        }
    }
    
    0 讨论(0)
提交回复
热议问题