我一直在尝试从下面抓取控制台输出到
private void List_Adapter()
{
using (Process tshark = new Process())
{
tshark.StartInfo.FileName = ConfigurationManager.AppSettings["fileLocation"];
tshark.StartInfo.Arguments = "-D";
tshark.StartInfo.CreateNoWindow = true;
tshark.StartInfo.UseShellExecute = false;
tshark.StartInfo.RedirectStandardOutput = true;
tshark.OutputDataReceived += new DataReceivedEventHandler(TSharkOutputHandler);
tshark.Start();
tshark.BeginOutputReadLine();
tshark.WaitForExit();
}
}
void TSharkOutputHandler(object sender, DataReceivedEventArgs e)
{
this.Dispatcher.Invoke((Action)(() =>
{
tboxConsoleOutput.AppendText(e.Data);
}));
}
但是 ui 只是卡住,没有显示任何信息,我只是错误地接近了这个
我找到了以下内容,但没有成功
No access different thread
Object different thread
Redirect Output to Textbox
Output to Textbox
Process output to richtextbox
最佳答案
我是这样做的:
首先你实现下面的类:
public class TextBoxConsole : TextWriter
{
TextBox output = null; //Textbox used to show Console's output.
/// <summary>
/// Custom TextBox-Class used to print the Console output.
/// </summary>
/// <param name="_output">Textbox used to show Console's output.</param>
public TextBoxConsole(TextBox _output)
{
output = _output;
output.ScrollBars = ScrollBars.Both;
output.WordWrap = true;
}
//<summary>
//Appends text to the textbox and to the logfile
//</summary>
//<param name="value">Input-string which is appended to the textbox.</param>
public override void Write(char value)
{
base.Write(value);
output.AppendText(value.ToString());//Append char to the textbox
}
public override Encoding Encoding
{
get { return System.Text.Encoding.UTF8; }
}
}
现在,如果您希望将所有控制台输出写入某个文本框,请按如下方式声明。
首先创建一个文本框并命名为“tbConsole”。现在你想告诉它做什么:
TextWriter writer = new TextBoxConsole(tbConsole);
Console.SetOut(writer);
从现在开始,每次您编写类似 Console.WriteLine("Foo");
的内容时,它都会写入您的文本框。
就是这样。备注this approach is not mine .此外,根据您的控制台产生的输出量,它可能性能不佳,因为它通过 char
写入输出 char
。
关于c# - 控制台输出到文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26528695/