c#控制台输出到form

.NET上控制台输出的实时截取(原文标题)

.NET上控制台输出的实时截取分两种不同的情况:截取子进程的输出和截取当前进程的输出。

截取子进程的输出可以使用Process.StandardOutput属性取得一个StreamReader,并用它来读取输出。注意读取操作是阻塞的,可以使用异步方法调用或者Process.BeginOutputReadLine()来进行异步读取。例子如下:

Process p = new Process();

p.StartInfo.UseShellExecute = false; // 必须

p.StartInfo.RedirectStandardOutput = true; // 必须

p.StartInfo.FileName = "SomeApp.exe";

p.Start();

string output = p.StandardOutput.ReadToEnd();

p.WaitForExit();

截取当前进程的输出可以使用Console.SetOut()。使用这种方法需要从TextWriter派生一个类,用于接收输出。但这个方法有个缺陷,就是只能截获Console类的输出,而对非托管的C运行库printf的输出不起作用。哪位高人知道解决方法的话望赐教。例子如下:

Console.SetOut(new TextBoxWriter(textBox1));

class TextBoxWriter : TextWriter

{

TextBox textBox;

delegate void WriteFunc(string value);

WriteFunc write;

WriteFunc writeLine;

public TextBoxWriter(TextBox textBox)

{

this.textBox = textBox;

write = Write;

writeLine = WriteLine;

}

// 使用UTF-16避免不必要的编码转换

public override Encoding Encoding

{

get { return Encoding.Unicode; }

}

// 最低限度需要重写的方法

public override void Write(string value)

{

if (textBox.InvokeRequired)

textBox.BeginInvoke(write, value);

else

textBox.AppendText(value);

}

// 为提高效率直接处理一行的输出

public override void WriteLine(string value)

{

if (textBox.InvokeRequired)

textBox.BeginInvoke(writeLine, value);

else

{

textBox.AppendText(value);

textBox.AppendText(this.NewLine);

}

}

}

我想把上面例子改成VB.Net的,新手,还不是很会改。