The console can redirect it's output to any textwriter. If you implement a textwriter that writes to Diagnostics.Debug, you are all set.
Here's a textwriter that writes to the debugger.
using System.Diagnostics;
using System.IO;
using System.Text;
namespace TestConsole
{
public class DebugTextWriter : TextWriter
{
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
//Required
public override void Write(char value)
{
Debug.Write(value);
}
//Added for efficiency
public override void Write(string value)
{
Debug.Write(value);
}
//Added for efficiency
public override void WriteLine(string value)
{
Debug.WriteLine(value);
}
}
}
Since it uses Diagnostics.Debug it will adhere to your compiler settings to wether it should write any output or not. This output can also be seen in Sysinternals DebugView.
Here's how you use it:
using System;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
Console.SetOut(new DebugTextWriter());
Console.WriteLine("This text goes to the Visual Studio output window.");
}
}
}
If you want to see the output in Sysinternals DebugView when you are compiling in Release mode, you can use a TextWriter that writes to the OutputDebugString API. It could look like this:
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace TestConsole
{
public class OutputDebugStringTextWriter : TextWriter
{
[DllImport("kernel32.dll")]
static extern void OutputDebugString(string lpOutputString);
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
//Required
public override void Write(char value)
{
OutputDebugString(value.ToString());
}
//Added for efficiency
public override void Write(string value)
{
OutputDebugString(value);
}
//Added for efficiency
public override void WriteLine(string value)
{
OutputDebugString(value);
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…